# -*- coding: utf-8 -*-
# 请认准 VNPY官方网站 http://www.vnpy.cn
import webbrowser
import numpy as np
# K线图
import pyqtgraph as pg
from PyQt5 import QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from pyqtgraph import QtCore, QtGui
from PyQt5.QtWidgets import QVBoxLayout, QWidget, QDialog, QPushButton, QMessageBox
import time
import os
import configparser
from PyQt5.QtCore import *

import entry_talib
import globalvar
import entry_combinekline
import pandas as pd
import talib as ta

# K线图
global lasttime, kid
kid = 0
lasttime = -1.0


class CandlestickItem(pg.GraphicsObject):
    def __init__(self, data):
        pg.GraphicsObject.__init__(self)
        self.data = data  ## data must have fields: time, open, close, min, max
        self.generatepicture()

    def generatepicture(self):
        self.picture = QtGui.QPicture()
        p = QtGui.QPainter(self.picture)
        p.setPen(pg.mkPen('w'))
        # print('输出A：'+str(len(self.data)))
        if len(self.data) == 0:
            pass
        elif len(self.data) == 1:
            if str(self.data) == '[(0, 0, 0, 0, 0, 0, 0)]':
                return
            else:
                w = 0.5
                for (t, tradingday, klinetime, open, close, min, max) in self.data:
                    p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
                    if open > close:
                        p.setBrush(pg.mkBrush('g'))
                    else:
                        p.setBrush(pg.mkBrush('r'))
                    p.drawRect(QtCore.QRectF(t - w, open, w * 2, close - open))
        else:
            w = (self.data[1][0] - self.data[0][0]) / 3
            for (t, tradingday, klinetime, open, close, min, max) in self.data:
                p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
                if open > close:
                    p.setBrush(pg.mkBrush('g'))
                else:
                    p.setBrush(pg.mkBrush('r'))
                p.drawRect(QtCore.QRectF(t - w, open, w * 2, close - open))
        p.end()

    def paint(self, p, *args):
        p.drawPicture(0, 0, self.picture)

    def boundingRect(self):
        return QtCore.QRectF(self.picture.boundingRect())


# global logYdata
# pyqtgraph分时图
data_market = []
# pyqtgraph资金曲线图
data_backtesting = []
# pyqtgraph实时资金曲线图
data_realtimecurve = []
# pyqtgraph K线
## 数据对应关系 (id, TradingDay, KlineTime,  open, close, min, ma).
data_kline = [(0, 0, 0, 0, 0, 0, 0), ]
count = 0


# 对话框
class DialogOptionsWidget(QWidget):
    def __init__(self, parent=None):
        super(DialogOptionsWidget, self).__init__(parent)

    def addCheckBox(self, text, value):
        pass




class StandardDialog(QDialog):
    def __init__(self, parent=None):
        super(StandardDialog, self).__init__(parent)

        self.setWindowTitle("Standard Dialog")

        frameStyle = QFrame.Sunken | QFrame.Panel

        mainLayout = QVBoxLayout(self)
        toolbox = QToolBox()
        mainLayout.addWidget(toolbox)

        self.errorMessageDialog = QErrorMessage(self)
        pushButton_integer = QPushButton("QInputDialog.get&Int()")
        pushButton_double = QPushButton("QInputDialog.get&Double()")
        pushButton_item = QPushButton("QInputDialog.getIte&m()")
        pushButton_text = QPushButton("QInputDialog.get&Text()")
        pushButton_multiLineText = QPushButton("QInputDialog.get&MultiLineText()")
        pushButton_color = QPushButton("QColorDialog.get&Color()")
        pushButton_font = QPushButton("QFontDialog.get&Font()")
        pushButton_directory = QPushButton("QFileDialog.getE&xistingDirectory()")
        pushButton_openFileName = QPushButton("QFileDialog.get&OpenFileName()")
        pushButton_openFileNames = QPushButton("QFileDialog.&getOpenFileNames()")
        pushButton_saveFileName = QPushButton("QFileDialog.get&SaveFileName()")
        pushButton_critical = QPushButton("QMessageBox.critica&l()")
        pushButton_information = QPushButton("QMessageBox.i&nformation()")
        pushButton_question = QPushButton("QQMessageBox.&question()")
        pushButton_warning = QPushButton("QMessageBox.&warning()")
        pushButton_error = QPushButton("QErrorMessage.showM&essage()")

        self.label_integer = QLabel()
        self.label_double = QLabel()
        self.label_item = QLabel()
        self.label_text = QLabel()
        self.label_multiLineText = QLabel()
        self.label_color = QLabel()
        self.label_font = QLabel()
        self.label_directory = QLabel()
        self.label_openFileName = QLabel()
        self.label_openFileNames = QLabel()
        self.label_saveFileName = QLabel()
        self.label_critical = QLabel()
        self.label_information = QLabel()
        self.label_question = QLabel()
        self.label_warning = QLabel()
        self.label_error = QLabel()

        self.label_integer.setFrameStyle(frameStyle)
        self.label_double.setFrameStyle(frameStyle)
        self.label_item.setFrameStyle(frameStyle)
        self.label_text.setFrameStyle(frameStyle)
        self.label_multiLineText.setFrameStyle(frameStyle)
        self.label_color.setFrameStyle(frameStyle)
        self.label_font.setFrameStyle(frameStyle)
        self.label_directory.setFrameStyle(frameStyle)
        self.label_openFileName.setFrameStyle(frameStyle)
        self.label_openFileNames.setFrameStyle(frameStyle)
        self.label_saveFileName.setFrameStyle(frameStyle)
        self.label_critical.setFrameStyle(frameStyle)
        self.label_information.setFrameStyle(frameStyle)
        self.label_question.setFrameStyle(frameStyle)
        self.label_warning.setFrameStyle(frameStyle)
        self.label_error.setFrameStyle(frameStyle)

        page = QWidget()
        layout = QGridLayout(page)
        layout.setColumnStretch(1, 1)
        layout.setColumnMinimumWidth(1, 250)
        '''
        layout.addWidget(pushButton_integer, 0, 0)
        layout.addWidget(self.label_integer, 0, 1)
        layout.addWidget(pushButton_double, 1, 0)
        layout.addWidget(self.label_double, 1, 1)
        layout.addWidget(pushButton_item, 2, 0)
        layout.addWidget(self.label_item, 2, 1)
        layout.addWidget(pushButton_text, 3, 0)
        layout.addWidget(self.label_text, 3, 1)
        layout.addWidget(pushButton_multiLineText, 4, 0)
        layout.addWidget(self.label_multiLineText, 4, 1)
        '''
        layout.addWidget(pushButton_integer)
        layout.addWidget(self.label_integer)
        layout.addWidget(pushButton_double)
        layout.addWidget(self.label_double)
        layout.addWidget(pushButton_item)
        layout.addWidget(self.label_item)
        layout.addWidget(pushButton_text)
        layout.addWidget(self.label_text)
        layout.addWidget(pushButton_multiLineText)
        layout.addWidget(self.label_multiLineText)
        layout.addItem(QSpacerItem(0, 0, QSizePolicy.Ignored, QSizePolicy.MinimumExpanding), 5, 0)
        toolbox.addItem(page, "Input Dialog")

        page = QWidget()
        layout = QGridLayout(page)
        layout.setColumnStretch(1, 1)
        layout.setColumnMinimumWidth(1, 250)
        layout.addWidget(pushButton_color)
        layout.addWidget(self.label_color)
        '''
        layout.addWidget(pushButton_color, 0, 0)
        layout.addWidget(self.label_color, 0, 1)
        '''
        colorDialogOptionsWidget = DialogOptionsWidget()
        colorDialogOptionsWidget.addCheckBox("Do not use native dialog", QColorDialog.DontUseNativeDialog)
        colorDialogOptionsWidget.addCheckBox("Show alpha channel", QColorDialog.ShowAlphaChannel)
        colorDialogOptionsWidget.addCheckBox("No buttons", QColorDialog.NoButtons)
        layout.addItem(QSpacerItem(0, 0, QSizePolicy.Ignored, QSizePolicy.MinimumExpanding), 1, 0)
        # layout.addWidget(colorDialogOptionsWidget, 2, 0, 1, 2)
        layout.addWidget(colorDialogOptionsWidget)
        toolbox.addItem(page, "Color Dialog")

        page = QWidget()
        layout = QGridLayout(page)
        layout.setColumnStretch(1, 1)
        layout.addWidget(pushButton_font)
        layout.addWidget(self.label_font)
        '''
        layout.addWidget(pushButton_font, 0, 0)
        layout.addWidget(self.label_font, 0, 1)
        '''
        fontDialogOptionsWidget = DialogOptionsWidget()
        fontDialogOptionsWidget.addCheckBox("Do not use native dialog", QFontDialog.DontUseNativeDialog)
        fontDialogOptionsWidget.addCheckBox("No buttons", QFontDialog.NoButtons)
        layout.addItem(QSpacerItem(0, 0, QSizePolicy.Ignored, QSizePolicy.MinimumExpanding), 1, 0)
        # layout.addWidget(fontDialogOptionsWidget, 2, 0, 1, 2)
        layout.addWidget(fontDialogOptionsWidget)
        toolbox.addItem(page, "Font Dialog")

        page = QWidget()
        layout = QGridLayout(page)
        layout.setColumnStretch(1, 1)
        '''
        layout.addWidget(pushButton_directory, 0, 0)
        layout.addWidget(self.label_directory, 0, 1)
        layout.addWidget(pushButton_openFileName, 1, 0)
        layout.addWidget(self.label_openFileName, 1, 1)
        layout.addWidget(pushButton_openFileNames, 2, 0)
        layout.addWidget(self.label_openFileNames, 2, 1)
        layout.addWidget(pushButton_saveFileName, 3, 0)
        layout.addWidget(self.label_saveFileName, 3, 1)
        '''
        layout.addWidget(pushButton_directory)
        layout.addWidget(self.label_directory)
        layout.addWidget(pushButton_openFileName)
        layout.addWidget(self.label_openFileName)
        layout.addWidget(pushButton_openFileNames)
        layout.addWidget(self.label_openFileNames)
        layout.addWidget(pushButton_saveFileName)
        layout.addWidget(self.label_saveFileName)
        fileDialogOptionsWidget = DialogOptionsWidget()
        fileDialogOptionsWidget.addCheckBox("Do not use native dialog", QFileDialog.DontUseNativeDialog)
        fileDialogOptionsWidget.addCheckBox("Show directories only", QFileDialog.ShowDirsOnly)
        fileDialogOptionsWidget.addCheckBox("Do not resolve symlinks", QFileDialog.DontResolveSymlinks)
        fileDialogOptionsWidget.addCheckBox("Do not confirm overwrite", QFileDialog.DontConfirmOverwrite)
        fileDialogOptionsWidget.addCheckBox("Do not use sheet", QFileDialog.DontUseSheet)
        fileDialogOptionsWidget.addCheckBox("Readonly", QFileDialog.ReadOnly)
        fileDialogOptionsWidget.addCheckBox("Hide name filter details", QFileDialog.HideNameFilterDetails)
        layout.addItem(QSpacerItem(0, 0, QSizePolicy.Ignored, QSizePolicy.MinimumExpanding), 4, 0)
        layout.addWidget(fileDialogOptionsWidget)
        toolbox.addItem(page, "File Dialogs")

        page = QWidget()
        layout = QGridLayout(page)
        layout.setColumnStretch(1, 1)
        '''
        layout.addWidget(pushButton_critical, 0, 0)
        layout.addWidget(self.label_critical, 0, 1)
        layout.addWidget(pushButton_information, 1, 0)
        layout.addWidget(self.label_information, 1, 1)
        layout.addWidget(pushButton_question, 2, 0)
        layout.addWidget(self.label_question, 2, 1)
        layout.addWidget(pushButton_warning, 3, 0)
        layout.addWidget(self.label_warning, 3, 1)
        layout.addWidget(pushButton_error, 4, 0)
        layout.addWidget(self.label_error, 4, 1)
        '''
        layout.addWidget(pushButton_critical)
        layout.addWidget(self.label_critical)
        layout.addWidget(pushButton_information)
        layout.addWidget(self.label_information)
        layout.addWidget(pushButton_question)
        layout.addWidget(self.label_question)
        layout.addWidget(pushButton_warning)
        layout.addWidget(self.label_warning)
        layout.addWidget(pushButton_error)
        layout.addWidget(self.label_error)
        layout.addItem(QSpacerItem(0, 0, QSizePolicy.Ignored, QSizePolicy.MinimumExpanding), 5, 0)
        toolbox.addItem(page, "Message Boxes")

        pushButton_integer.clicked.connect(self.setInteger)
        pushButton_double.clicked.connect(self.setDouble)
        pushButton_item.clicked.connect(self.setItem)
        pushButton_text.clicked.connect(self.setText)
        pushButton_multiLineText.clicked.connect(self.setMultiLineText)
        pushButton_color.clicked.connect(self.setColor)
        pushButton_font.clicked.connect(self.setFont)
        pushButton_directory.clicked.connect(self.setExistingDirectory)
        pushButton_openFileName.clicked.connect(self.setOpenFileName)
        pushButton_openFileNames.clicked.connect(self.setOpenFileNames)
        pushButton_saveFileName.clicked.connect(self.setsavefilename)
        pushButton_critical.clicked.connect(self.criticalmessage)
        pushButton_information.clicked.connect(self.informationmessage)
        pushButton_question.clicked.connect(self.questionmessage)
        pushButton_warning.clicked.connect(self.warningmessage)
        pushButton_error.clicked.connect(self.errormessage)




    # 输入对话框 取整数
    def setInteger(self):
        intNum, ok = QInputDialog.getInt(self, "QInputDialog.getInteger()", "Percentage:", 25, 0, 100, 1)
        if ok:
            self.label_integer.setText(str(intNum))

    # 输入对话框 取实数
    def setDouble(self):
        doubleNum, ok = QInputDialog.getDouble(self, "QInputDialog.getDouble()", "Amount:", 37.56, -10000, 10000, 2)
        if ok:
            self.label_double.setText(str(doubleNum))

    # 输入对话框 取列表项
    def setItem(self):
        items = ["Spring", "Summer", "Fall", "Winter"]
        item, ok = QInputDialog.getItem(self, "QInputDialog.getItem()", "Season:", items, 0, False)
        if ok and item:
            self.label_item.setText(item)

    # 输入对话框 取文本
    def setText(self):
        text, ok = QInputDialog.getText(self, "QInputDialog.getText()", "User name:", QLineEdit.Normal,
                                        QDir.home().dirName())
        if ok and text:
            self.label_text.setText(text)

    # 输入对话框 取多行文本
    def setMultiLineText(self):
        text, ok = QInputDialog.getMultiLineText(self, "QInputDialog.getMultiLineText()", "Address:",
                                                 "John Doe\nFreedom Street")
        if ok and text:
            self.label_multiLineText.setText(text)

    # 颜色对话框 取颜色
    def setColor(self):
        # options = QColorDialog.ColorDialogOptions(QFlag.QFlag(colorDialogOptionsWidget.value()))
        color = QColorDialog.getColor(Qt.green, self, "Select Color")
        if color.isValid():
            self.label_color.setText(color.name())
            self.label_color.setPalette(QPalette(color))
            self.label_color.setAutoFillBackground(True)

    # 字体对话框 取字体
    def setFont(self):
        # options = QFontDialog.FontDialogOptions(QFlag(fontDialogOptionsWidget.value()))
        # font, ok = QFontDialog.getFont(ok, QFont(self.label_font.text()), self, "Select Font",options)
        font, ok = QFontDialog.getFont()
        if ok:
            self.label_font.setText(font.key())
            self.label_font.setFont(font)

    # 目录对话框 取目录


def setExistingDirectory(self):
    # options = QFileDialog.Options(QFlag(fileDialogOptionsWidget->value()))
    # options |= QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly
    directory = QFileDialog.getExistingDirectory(self,
                                                 "QFileDialog.getExistingDirectory()",
                                                 self.label_directory.text())
    if directory:
        self.label_directory.setText(directory)

    # 打开文件对话框 取文件名


def setOpenFileName(self):
    # options = QFileDialog.Options(QFlag(fileDialogOptionsWidget.value()))
    # selectedFilter
    fileName, filetype = QFileDialog.getOpenFileName(self,
                                                     "QFileDialog.getOpenFileName()",
                                                     self.label_openFileName.text(),
                                                     "All Files (*);;Text Files (*.txt)")
    if fileName:
        self.label_openFileName.setText(fileName)

    # 打开文件对话框 取一组文件名


def setOpenFileNames(self):
    # options = QFileDialog.Options(QFlag(fileDialogOptionsWidget.value()))
    # selectedFilter
    openFilesPath = "D:/documents/pyMarksix/draw/"
    files, ok = QFileDialog.getOpenFileNames(self,
                                             "QFileDialog.getOpenFileNames()",
                                             openFilesPath,
                                             "All Files (*);;Text Files (*.txt)")

    if len(files):
        self.label_openFileNames.setText(", ".join(files))

    # 保存文件对话框 取文件名


def setsavefilename(self):
    # options = QFileDialog.Options(QFlag(fileDialogOptionsWidget.value()))
    # selectedFilter
    fileName, ok = QFileDialog.getSaveFileName(self,
                                               "QFileDialog.getSaveFileName()",
                                               self.label_saveFileName.text(),
                                               "All Files (*);;Text Files (*.txt)")
    if fileName:
        self.label_saveFileName.setText(fileName)


def criticalmessage(self):
    # reply = QMessageBox.StandardButton()
    MESSAGE = "批评！"
    reply = QMessageBox.critical(self,
                                 "QMessageBox.critical()",
                                 MESSAGE,
                                 QMessageBox.Abort | QMessageBox.Retry | QMessageBox.Ignore)
    if reply == QMessageBox.Abort:
        self.label_critical.setText("Abort")
    elif reply == QMessageBox.Retry:
        self.label_critical.setText("Retry")
    else:
        self.label_critical.setText("Ignore")


def informationmessage(self):
    MESSAGE = "信息"
    reply = QMessageBox.information(self, "QMessageBox.information()", MESSAGE)
    if reply == QMessageBox.Ok:
        self.label_information.setText("OK")
    else:
        self.label_information.setText("Escape")


def questionmessage(self):
    MESSAGE = "疑问"
    reply = QMessageBox.question(self, "QMessageBox.question()",
                                 MESSAGE,
                                 QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
    if reply == QMessageBox.Yes:
        self.label_question.setText("Yes")
    elif reply == QMessageBox.No:
        self.label_question.setText("No")
    else:
        self.label_question.setText("Cancel")


def warningmessage(self):
    MESSAGE = "警告文本"
    msgBox = QMessageBox(QMessageBox.Warning,
                         "QMessageBox.warning()",
                         MESSAGE,
                         QMessageBox.Retry | QMessageBox.Discard | QMessageBox.Cancel,
                         self)
    msgBox.setDetailedText("详细信息。。。")
    # msgBox.addButton("Save &Again", QMessageBox.AcceptRole)
    # msgBox.addButton("&Continue", QMessageBox.RejectRole)
    if msgBox.exec() == QMessageBox.AcceptRole:
        self.label_warning.setText("Retry")
    else:
        self.label_warning.setText("Abort")


def errormessage(self):
    self.errorMessageDialog.showMessage(
        "This dialog shows and remembers error messages. "
        "If the checkbox is checked (as it is by default), "
        "the shown message will be shown again, "
        "but if the user unchecks the box the message "
        "will not appear again if QErrorMessage.showMessage() "
        "is called with the same message.")
    self.label_error.setText("If the box is unchecked, the message "
                             "won't appear again.")


tradestate = 0
backteststate = 0
global markettj
markettj = 0
global config


class Ui_MainWindow(object):

    '''
    def closeEvent(self, event):
        close = QMessageBox.question(self,
                                     "QUIT",
                                     "Sure?",
                                      QMessageBox.Yes | QMessageBox.No)
        if close == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def closeEvent(self, event):
        self.dlg_talibindicatrix.close()
        reply = QMessageBox.question(self, 'Message', 'Are you want to quit?', QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.Yes)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()
            
    '''


        #self.dlg_talibindicatrix.close()

    def update_depthMarketData(self, Price, InstrumentID):
        # uimarketthread = UIUpdatemarketThread(a.contents.LastPrice)
        # uimarketthread.start()
        # uiklinethread = UIUpdateklineThread(a.contents.LastPrice)
        # uiklinethread.start()
        self.updatemarketUi(Price)
        self.updateklineUi(InstrumentID)

    global markettj

    def log_marketdata(self, mystr):
        global markettj
        markettj = markettj + 1
        if markettj > 14:
            self.list_marketdata.clear()
            markettj = 0
        _translate = QtCore.QCoreApplication.translate
        item = QtWidgets.QListWidgetItem()
        self.list_marketdata.addItem(item)
        item = self.list_marketdata.item(self.list_marketdata.count() - 1)
        tstr = time.strftime("%Y-%m-%d %H:%M:%S ", time.localtime())
        item.setText(_translate("MainWindow", tstr + mystr))

    def callback_md_tick(self, a):
        # 将线程的参数传入
        self.log_marketdata(str(a[0], encoding="utf-8") + "%.2f" % a[1])
        # self.signal_md_tick.emit([a.contents.InstrumentID, a.contents.LastPrice, a.contents.Volume, a.contents.TradingDay, a.contents.UpdateTime, a.contents.UpdateMillisec])
        if globalvar.caompareinstrumwent(str(a[0], encoding="utf-8")):
            self.update_depthMarketData(a[1], a[0])

    def mounthyear4(self, thisdate, add):
        year = int(thisdate * 0.01)
        mounth = thisdate - year * 100
        mounth = mounth + add
        if mounth > 12:
            mounth = mounth - 12
            year = year + 1
        thisdate = year * 100 + mounth
        return thisdate

    def mounthyear3(self, thisdate, add):
        year = int(thisdate * 0.01)
        y = int(thisdate * 0.001)
        mounth = thisdate - year * 100
        mounth = mounth + add
        if mounth > 12:
            mounth = mounth - 12
            year = year + 1
        thisdate = year * 100 + mounth
        thisdate = thisdate - 1000 * y
        return thisdate

    def MakeInsutrumentID(self, instrumentMain, instrumentName, exchange, templist):
        global tempdate
        returnvalue = 0
        savedate = time.strftime("%Y%m%d", time.localtime())
        tvs = (int(float(savedate) * 0.000001)) * 1000000
        tempdate = int((float(savedate) - float(tvs)) * 0.01)
        tj = 0
        for j in range(12):
            if exchange == 'INE':
                returnvalue = self.mounthyear4(tempdate, j)
                if len(instrumentMain) > 0:
                    templist.append(instrumentMain + str(returnvalue))
            elif exchange == 'CFFEX':
                returnvalue = self.mounthyear4(tempdate, j)
                if len(instrumentMain) > 0:
                    templist.append(instrumentMain + str(returnvalue))
            elif exchange == 'SHFE':
                returnvalue = self.mounthyear4(tempdate, j)
                if len(instrumentMain) > 0:
                    templist.append(instrumentMain + str(returnvalue))
            elif exchange == 'DCE':
                returnvalue = self.mounthyear4(tempdate, j)
                if len(instrumentMain) > 0:
                    templist.append(instrumentMain + str(returnvalue))
            elif exchange == 'CZCE':
                returnvalue = self.mounthyear3(tempdate, j)
                if len(instrumentMain) > 0:
                    templist.append(instrumentMain + str(returnvalue))
        return returnvalue

    dict_period = {'K线周期: M1': '1min', 'K线周期: M3': '3min',
                   'K线周期: M5': '5min', 'K线周期: M10': '10min',
                   'K线周期: M15': '15min', 'K线周期: M30': '30min',
                   'K线周期: M60': '60min', 'K线周期: M120': '120min',
                   'K线周期: D1': '1d'
                   }

    dict_period2 = {1: '1min', 3: '3min',
                    5: '5min', 10: '10min',
                    15: '15min', 30: '30min',
                    60: '60min', 120: '120min',
                    9999001: '1d'
                    }

    dict_period3 = {'K线周期: M1': 1, 'K线周期: M3': 3,
                   'K线周期: M5': 5, 'K线周期: M10': 10,
                   'K线周期: M15': 15, 'K线周期: M30': 30,
                   'K线周期: M60': 60, 'K线周期: M120': 120,
                   'K线周期: D1': 9999001
                   }

    dict_comboBox_kline_index = {1: 0, 3: 1,
                                 5: 2, 10: 3,
                                 15: 4, 30: 5,
                                 60: 6, 120: 7,
                                 9999001: 8
                                 }

    # 从服务器获取M1周期K线数据
    def GetKlineFromeServer(self):
        global data_kline, data_market
        self.plt_kline.clear()
        data_kline = [(0, 0, 0, 0, 0, 0, 0), ]
        globalvar.data_kline_M1.clear()
        data_market.clear()
        thisInstrument = str(globalvar.selectinstrumenid)
        try:
            # 清空该合约 DataFrame 数据
            if len(globalvar.dict_dataframe_kline_M1[thisInstrument]) > 0:
                globalvar.dict_dataframe_kline_M1[thisInstrument].drop(
                    globalvar.dict_dataframe_kline_M1[thisInstrument].index, inplace=True)
        except Exception as e:
            print("dict_dataframe_kline_M1 is empty: " + repr(e))
            globalvar.dict_dataframe_kline_M1[thisInstrument] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [], 'vol': []}, index=[])

        self.plt_kline.enableAutoRange(axis='y')
        self.plt_kline.setAutoVisible(y=False)
        # print('globalvar.thistoday: '+ str(globalvar.thistoday))
        # if globalvar.thistoday == 0:
        globalvar.thistoday = globalvar.vk.GetTradingDay()
        if globalvar.thistoday < 19000000:
            print("起始交易日错误" + str(globalvar.thistoday))
            return
        if globalvar.klineserverstate == 0:
            self.updateklineUi(globalvar.selectinstrumenid)
        elif globalvar.klineserverstate == 1:
            # 从服务器获取当日M1周期K线数据
            globalvar.vk.GetServerKline(thisInstrument, int(globalvar.thistoday))
            self.UpdateKlineUIFromFile(globalvar.selectinstrumenid, int(globalvar.thistoday))
            self.comboBox_kline.setCurrentIndex(self.dict_comboBox_kline_index[globalvar.selectperiod])
            # K线图切换到最后一次保存的周期，重新绘图
            self.ChangePeriodCharts_klineperiod(globalvar.selectperiod)
        elif globalvar.klineserverstate == 2:
            # 从服务器获取多日M1周期K线数据（需Plus会员）
            if globalvar.vk.GetServerMultiKline(thisInstrument, int(globalvar.thistoday), 10,
                                                globalvar.Plus_UserName, globalvar.Plus_Password) == 1:
                self.UpdateMultiKlineUIFromFile(globalvar.selectinstrumenid, int(globalvar.thistoday))
                globalvar.PlusAuthState = 1
                self.comboBox_kline.setCurrentIndex(self.dict_comboBox_kline_index[globalvar.selectperiod])
                # K线图切换到最后一次保存的周期，重新绘图
                self.ChangePeriodCharts_klineperiod(globalvar.selectperiod)
            else:
                webbrowser.open('http://www.vnpy.cn/qplus.html')

    # 从内存获取K线 M1周期数据
    def GetKlineFromeMemory(self, df, period_type):
        global data_kline, data_market
        self.plt_kline.clear()
        data_kline = [(0, 0, 0, 0, 0, 0, 0), ]
        globalvar.data_kline_M1.clear()
        data_market.clear()
        thisInstrument = str(globalvar.selectinstrumenid)
        self.plt_kline.enableAutoRange(axis='y')
        self.plt_kline.setAutoVisible(y=False)
        if globalvar.thistoday == 0:
            globalvar.thistoday = globalvar.vk.GetTradingDay()
        if globalvar.thistoday < 19000000:
            print("起始交易日错误" + str(globalvar.thistoday))
            return
        self.UpdateKlineChartsBycombox(globalvar.selectinstrumenid, period_type, df)

    # 由M1周期数据，通过DataFrame方式生成选中combox 周期的K线数据，并更新K线图表
    def UpdateKlineChartsBycombox(self, InstrumentID, period_type, df):
        global data_kline_M1
        data_kline_M1 = [(0, 0, 0, 0, 0, 0, 0), ]
        try:
            cid = 1
            globalvar.ticklist = []
            for index, row in df.iterrows():
                # if lastdatetime != str(row['datetime']):
                # ld = line.split(',')
                temp = (cid,
                        float(str(row['tradingday'])),
                        float(str(row['klinetime'])),
                        float(str(row['open'])),
                        float(str(row['close'])),
                        float(str(row['low'])),
                        float(str(row['high'])))
                globalvar.data_kline_M1.append(temp)

                tempstr = str(int(float(row['klinetime']) * 10000))
                tempstr_list = list(tempstr)
                tempstr_list.insert(len(tempstr_list) - 2, ':')
                tempstr = ''.join(tempstr_list)
                globalvar.ticklist.append(str(row['tradingday']) + "\n" + tempstr)

                cid = cid + 1
            self.plt_kline.removeItem(self.item)
            self.item = CandlestickItem(globalvar.data_kline_M1)  # 原始数据,对应（0,0）幅图
            try:
                self.plt_kline.addItem(self.item)
            except Exception as e:
                print("UpdateKlineChartsBycombox Error:" + repr(e))

            # 横坐标刻度
            xax = self.plt_kline.getAxis('bottom')  # 坐标轴x
            xdict = dict(enumerate(globalvar.ticklist))
            xax.setTicks([xdict.items()])
            # 根据M1周期K线合成M3周期K线数据
            # entry_combinekline.ComposeKlineUpdate(InstrumentID, "3min")
        except Exception as e:
            print("UpdateKlineChartsBycombox Error:" + repr(e))

    def InitKlineDataFrame(self, InstrumentID):
        try:
            if isinstance(globalvar.dict_dataframe_kline_M3[InstrumentID], pd.DataFrame):
                pass
        except Exception as e:
            globalvar.dict_dataframe_kline_M3[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            globalvar.dict_dataframe_kline_M5[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            globalvar.dict_dataframe_kline_M10[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            globalvar.dict_dataframe_kline_M15[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            globalvar.dict_dataframe_kline_M30[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            globalvar.dict_dataframe_kline_M60[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            globalvar.dict_dataframe_kline_M120[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            globalvar.dict_dataframe_kline_D1[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            print("InitKlineDataFrame Error:" + repr(e))

    # DataFrame数据预处理，由M1周期数据，通过DataFrame方式生成选中combox 周期的K线数据，并更新K线图表
    # 根据M1 K线数据生成多个周期的K线数据，以DataFrame格式存储在dataframe_kline目录下
    def combineklineUpdateCharts(self, InstrumentID, period_type):
        # 初始化该合约DataFrame类型的除M1周期以外所有周期的K线数据变量
        self.InitKlineDataFrame(InstrumentID)
        dict_period_dataframe_kline = {'K线周期: M1': globalvar.dict_dataframe_kline_M1[InstrumentID],
                                       'K线周期: M3': globalvar.dict_dataframe_kline_M3[InstrumentID],
                                       'K线周期: M5': globalvar.dict_dataframe_kline_M5[InstrumentID],
                                       'K线周期: M10': globalvar.dict_dataframe_kline_M10[InstrumentID],
                                       'K线周期: M15': globalvar.dict_dataframe_kline_M15[InstrumentID],
                                       'K线周期: M30': globalvar.dict_dataframe_kline_M30[InstrumentID],
                                       'K线周期: M60': globalvar.dict_dataframe_kline_M60[InstrumentID],
                                       'K线周期: M120': globalvar.dict_dataframe_kline_M120[InstrumentID],
                                       'K线周期: D1': globalvar.dict_dataframe_kline_D1[InstrumentID]
                                       }
        try:
            if not os.path.exists(("dataframe_kline\\" + InstrumentID)):
                os.mkdir("dataframe_kline\\" + InstrumentID)
            globalvar.dict_dataframe_kline_M1[InstrumentID].to_csv(
                "dataframe_kline\\" + InstrumentID + "\\kline_1min.csv", index=False)
            data = pd.read_csv("dataframe_kline\\" + InstrumentID + "\\kline_1min.csv", index_col='datetime',
                               parse_dates=True)
            grouper = data.groupby(
                [pd.Grouper(freq=period_type), 'recordid', 'tradingday', 'klinetime', 'instrumentid', 'open', 'close',
                 'low', 'high',
                 'vol'])
            df = pd.DataFrame(grouper['instrumentid'].count())
            df.rename(columns={'instrumentid': 'count'}, inplace=True)
            df.reset_index(inplace=True)
            del df['count']
            df2 = pd.DataFrame(
                {"datetime": [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [],
                 'low': [], 'high': [],
                 'vol': []}, index=[])

            lastdatetime = ""
            high = 0
            low = 0
            open = 0
            close = 0
            vol = 0
            instrumentid = ""
            datetime = ""
            tradingday = ""
            klinetime = ""
            recordid = 1
            for index, row in df.iterrows():
                if lastdatetime != str(row['datetime']):
                    if open > 0:
                        tempdata = {"datetime": datetime, "recordid": '{:0>8s}'.format(str(recordid)),
                                    "tradingday": tradingday, "klinetime": klinetime,
                                    "instrumentid": instrumentid,
                                    "open": open, "close": close, "low": low, "high": high, "vol": vol}
                        df2 = df2.append(tempdata, ignore_index=True)
                    recordid = int(row['recordid'])
                    open = float(row['open'])
                    low = float(row['low'])
                    high = float(row['high'])
                    close = float(row['close'])
                    vol = int(row['vol'])
                    lastdatetime = str(row['datetime'])
                    lastclose = row['close']
                    datetime = row['datetime']
                    instrumentid = row['instrumentid']
                    tradingday = row['tradingday']
                    klinetime = row['klinetime']
                else:
                    recordid = int(row['recordid'])
                    low = min(low, float(row['low']))
                    high = max(high, float(row['high']))
                    close = float(row['close'])
                    vol = vol + int(row['vol'])

            df2 = df2.sort_values(by='recordid')
            df2.to_csv("dataframe_kline\\" + InstrumentID + "\\kline_" + period_type + ".csv", index=True)
            dict_period_dataframe_kline[period_type] = df2.copy()

            # TALIB公式计算

            dw = pd.DataFrame()
            # KDJ 值对应的函数是 STOCH
            dw['slowk'], dw['slowd'] = ta.STOCH(df2['high'].values,
                                                df2['low'].values,
                                                df2['close'].values,
                                                fastk_period=9,
                                                slowk_period=3,
                                                slowk_matype=0,
                                                slowd_period=3,
                                                slowd_matype=0)

            # 求出J值，J = (3*K)-(2*D)
            dw['slowj'] = list(map(lambda x, y: 3 * x - 2 * y, dw['slowk'], dw['slowd']))
            dw.index = range(len(dw))
            print("talib: " + dw[-3:])


            # 从内存获取K线数据并更新K线图表
            self.GetKlineFromeMemory(dict_period_dataframe_kline[period_type], period_type)
        except Exception as e:
            print("combineklineUpdateCharts Error:" + repr(e))

    # 需要生成合约&周期的K线数据状态
    # 合约为dict,周期为list
    dict_instrument_period = {}

    # DataFrame数据预处理，由M1周期数据，后台方式计算，通过DataFrame方式生成选中combox 周期的K线数据，
    # 并根据M1 K线数据生成多个周期的K线数据，以DataFrame格式存储在dataframe_kline目录下
    def combineklineBackgroundCal(self, InstrumentID):
        # 初始化该合约DataFrame类型的除M1周期以外所有周期的K线数据变量
        self.InitKlineDataFrame(InstrumentID)
        dict_period_dataframe_kline = {'K线周期: M1': globalvar.dict_dataframe_kline_M1[InstrumentID],
                                       'K线周期: M3': globalvar.dict_dataframe_kline_M3[InstrumentID],
                                       'K线周期: M5': globalvar.dict_dataframe_kline_M5[InstrumentID],
                                       'K线周期: M10': globalvar.dict_dataframe_kline_M10[InstrumentID],
                                       'K线周期: M15': globalvar.dict_dataframe_kline_M15[InstrumentID],
                                       'K线周期: M30': globalvar.dict_dataframe_kline_M30[InstrumentID],
                                       'K线周期: M60': globalvar.dict_dataframe_kline_M60[InstrumentID],
                                       'K线周期: M120': globalvar.dict_dataframe_kline_M120[InstrumentID],
                                       'K线周期: D1': globalvar.dict_dataframe_kline_D1[InstrumentID]
                                       }
        try:
            if not os.path.exists(("dataframe_kline\\" + InstrumentID)):
                os.mkdir("dataframe_kline\\" + InstrumentID)
            globalvar.dict_dataframe_kline_M1[InstrumentID].to_csv(
                "dataframe_kline\\" + InstrumentID + "\\kline_1min.csv", index=False)
            data = pd.read_csv("dataframe_kline\\" + InstrumentID + "\\kline_1min.csv", index_col='datetime',
                               parse_dates=True)
            grouper = data.groupby(
                [pd.Grouper(freq=period_type), 'recordid', 'tradingday', 'klinetime', 'instrumentid', 'open', 'close',
                 'low', 'high',
                 'vol'])
            df = pd.DataFrame(grouper['instrumentid'].count())
            df.rename(columns={'instrumentid': 'count'}, inplace=True)
            df.reset_index(inplace=True)
            del df['count']
            df2 = pd.DataFrame(
                {"datetime": [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [],
                 'low': [], 'high': [],
                 'vol': []}, index=[])

            lastdatetime = ""
            high = 0
            low = 0
            open = 0
            close = 0
            vol = 0
            instrumentid = ""
            datetime = ""
            tradingday = ""
            klinetime = ""
            recordid = 1
            for index, row in df.iterrows():
                if lastdatetime != str(row['datetime']):
                    if open > 0:
                        tempdata = {"datetime": datetime, "recordid": '{:0>8s}'.format(str(recordid)),
                                    "tradingday": tradingday, "klinetime": klinetime,
                                    "instrumentid": instrumentid,
                                    "open": open, "close": close, "low": low, "high": high, "vol": vol}
                        df2 = df2.append(tempdata, ignore_index=True)
                    recordid = int(row['recordid'])
                    open = float(row['open'])
                    low = float(row['low'])
                    high = float(row['high'])
                    close = float(row['close'])
                    vol = int(row['vol'])
                    lastdatetime = str(row['datetime'])
                    lastclose = row['close']
                    datetime = row['datetime']
                    instrumentid = row['instrumentid']
                    tradingday = row['tradingday']
                    klinetime = row['klinetime']
                else:
                    recordid = int(row['recordid'])
                    low = min(low, float(row['low']))
                    high = max(high, float(row['high']))
                    close = float(row['close'])
                    vol = vol + int(row['vol'])

            df2 = df2.sort_values(by='recordid')
            df2.to_csv("dataframe_kline\\" + InstrumentID + "\\kline_" + period_type + ".csv", index=True)
            dict_period_dataframe_kline[period_type] = df2.copy()
            # 更新K线图表
            # self.UpdateKlineChartsBycombox(InstrumentID, period_type, dict_period_dataframe_kline[period_type])
            # self.GetKlineFromeMemory(dict_period_dataframe_kline[period_type],period_type)
        except Exception as e:
            print("combineklineBackgroundCal Error:" + repr(e))

    def to_comboBox_klineperiod(self, text):
        globalvar.selectperiod = self.dict_period3[text]
        self.combineklineUpdateCharts(globalvar.selectinstrumenid, self.dict_period[text])

    def ChangePeriodCharts_klineperiod(self, period):
        self.combineklineUpdateCharts(globalvar.selectinstrumenid, self.dict_period2[period])

    def Background_klineperiod(self):
        self.combineklineBackgroundCal(globalvar.selectinstrumenid)

    def to_comboBox_1(self, text):
        self.comboBox_instrument.clear()
        self.comboBox_instrumentid.clear()
        templist = text.split(",", -1)
        # templist2 = []
        # self.MakeInsutrumentID(templist[0],templist[1],templist[2],templist2)
        # self.comboBox_instrumentid.addItems(templist2)
        if templist[0] == 'ALL':
            self.comboBox_instrument.addItems(globalvar.list_INE)
            self.comboBox_instrument.addItems(globalvar.list_CFFEX)
            self.comboBox_instrument.addItems(globalvar.list_SHFE)
            self.comboBox_instrument.addItems(globalvar.list_DCE)
            self.comboBox_instrument.addItems(globalvar.list_CZCE)
        elif templist[0] == 'INE':
            self.comboBox_instrument.addItems(globalvar.list_INE)
            if len(globalvar.list_INE) > 0:
                templist2 = globalvar.list_INE[0].split(",", -1)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
                self.comboBox_instrumentid.clear()
                templist = globalvar.list_INE[0].split(",", -1)
                templist2 = []
                self.MakeInsutrumentID(templist[0], templist[1], templist[2], templist2)
                self.comboBox_instrumentid.addItems(templist2)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
        elif templist[0] == 'CFFEX':
            self.comboBox_instrument.addItems(globalvar.list_CFFEX)
            if len(globalvar.list_CFFEX) > 0:
                templist2 = globalvar.list_CFFEX[0].split(",", -1)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
                self.comboBox_instrumentid.clear()
                templist = globalvar.list_CFFEX[0].split(",", -1)
                templist2 = []
                self.MakeInsutrumentID(templist[0], templist[1], templist[2], templist2)
                self.comboBox_instrumentid.addItems(templist2)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
        elif templist[0] == 'SHFE':
            self.comboBox_instrument.addItems(globalvar.list_SHFE)
            if len(globalvar.list_SHFE) > 0:
                templist2 = globalvar.list_SHFE[0].split(",", -1)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
                self.comboBox_instrumentid.clear()
                templist = globalvar.list_SHFE[0].split(",", -1)
                templist2 = []
                self.MakeInsutrumentID(templist[0], templist[1], templist[2], templist2)
                self.comboBox_instrumentid.addItems(templist2)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
        elif templist[0] == 'DCE':
            self.comboBox_instrument.addItems(globalvar.list_DCE)
            if len(globalvar.list_DCE) > 0:
                templist2 = globalvar.list_DCE[0].split(",", -1)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
                self.comboBox_instrumentid.clear()
                templist = globalvar.list_DCE[0].split(",", -1)
                templist2 = []
                self.MakeInsutrumentID(templist[0], templist[1], templist[2], templist2)
                self.comboBox_instrumentid.addItems(templist2)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
        elif templist[0] == 'CZCE':
            self.comboBox_instrument.addItems(globalvar.list_CZCE)
            if len(globalvar.list_CZCE) > 0:
                templist2 = globalvar.list_CZCE[0].split(",", -1)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
                self.comboBox_instrumentid.clear()
                templist = globalvar.list_CZCE[0].split(",", -1)
                templist2 = []
                self.MakeInsutrumentID(templist[0], templist[1], templist[2], templist2)
                self.comboBox_instrumentid.addItems(templist2)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
        self.GetKlineFromeServer()

    def to_comboBox_2(self, text):
        self.comboBox_instrumentid.clear()
        templist = text.split(",", -1)
        templist2 = []
        self.MakeInsutrumentID(templist[0], templist[1], templist[2], templist2)
        self.comboBox_instrumentid.addItems(templist2)
        globalvar.selectinstrumenid = templist2[0]
        globalvar.rc.updatehistorystock(templist2[0])
        if templist[2] == 'ALL':
            self.comboBox_exchange.setCurrentText(templist[2] + ',全部交易所')
            globalvar.selectexchange = templist[2]
        elif templist[2] == 'INE':
            self.comboBox_exchange.setCurrentText(templist[2] + ',能源所')
            globalvar.selectexchange = templist[2]
        elif templist[2] == 'CFFEX':
            self.comboBox_exchange.setCurrentText(templist[2] + ',中金所')
            globalvar.selectexchange = templist[2]
        elif templist[2] == 'SHFE':
            self.comboBox_exchange.setCurrentText(templist[2] + ',上期所')
            globalvar.selectexchange = templist[2]
        elif templist[2] == 'DCE':
            self.comboBox_exchange.setCurrentText(templist[2] + ',大商所')
            globalvar.selectexchange = templist[2]
        elif templist[2] == 'CZCE':
            self.comboBox_exchange.setCurrentText(templist[2] + ',郑商所')
            globalvar.selectexchange = templist[2]
        self.GetKlineFromeServer()

    def to_comboBox_3(self, text):
        globalvar.selectinstrumenid = text
        globalvar.rc.updatehistorystock(text)
        self.GetKlineFromeServer()

    def change_comboBox(self, text):
        global dict_instrument, dict_instrument
        globalvar.rc.updatehistorystock(text)
        if text in globalvar.dict_exchange:
            self.comboBox_exchange.setCurrentText(str(globalvar.dict_exchange[text]))
            self.to_comboBox_1(str(globalvar.dict_exchange[text]))
            self.comboBox_instrument.setCurrentText(str(globalvar.dict_instrument[text]))
            self.to_comboBox_2(str(globalvar.dict_instrument[text]))
            self.comboBox_instrumentid.setCurrentText(text)
            self.to_comboBox_3(text)

    def callback_md_combox(self):
        self.comboBox_instrument.addItems(globalvar.list_INE)
        self.comboBox_instrument.addItems(globalvar.list_CFFEX)
        self.comboBox_instrument.addItems(globalvar.list_SHFE)
        self.comboBox_instrument.addItems(globalvar.list_DCE)
        self.comboBox_instrument.addItems(globalvar.list_CZCE)

    def move_button(self):
        # self.Button_h1
        pass

    def callback_td_info(self, msg):
        # 将线程的参数传入
        pass

    class DialogTradeConfirm(QtWidgets.QDialog):
        def __init__(self):
            super().__init__()
            self.initUI()

        def Function_InsertOrder(self):
            pass
            # result = result + globalvar.td.InsertOrder(str(marketdata.contents.InstrumentID, encoding="utf-8"), exchangeid,'1', '0',VN_OPT_LimitPrice , marketdata.contents.LastPrice-10, 1)

        def initUI(self):
            self.setWindowFlags(Qt.WindowCloseButtonHint)
            # self.btn_helper = QPushButton('选择期货公司', self)
            # self.btn_helper.move(380, 20)
            # self.btn_helper.clicked.connect(self.showDialog)
            self.label_1 = QLabel(self)
            self.label_1.setText("合约")
            self.label_1.move(60, 20)
            self.label_2 = QLabel(self)
            self.label_2.setText("方向")
            self.label_2.move(60, 55)
            self.label_3 = QLabel(self)
            self.label_3.setText("交易密码")
            self.label_3.move(60, 90)

            self.label_7 = QLabel(self)
            self.label_7.setText("输入格式 tcp://ip:port")
            self.label_7.resize(140, 30)
            self.label_7.move(380, 230)
            self.label_8 = QLabel(self)
            self.label_8.setText("APPID")
            self.label_8.move(60, 230)
            self.label_9 = QLabel(self)
            self.label_9.setText("AUTHCODE")
            self.label_9.move(60, 265)
            self.label_10 = QLabel(self)
            self.label_10.setText("ProductInfo")
            self.label_10.move(60, 300)
            self.btn_authcode = QPushButton('如何获取授权码？', self)
            self.btn_authcode.move(330, 265)
            self.btn_authcode.resize(130, 30)
            self.btn_authcode.clicked.connect(self.Function_InsertOrder)
            self.Edit_brokerid = QLineEdit(self)
            self.Edit_brokerid.move(160, 20)
            self.Edit_brokerid.resize(200, 30)
            self.Edit_investor = QLineEdit(self)
            self.Edit_investor.move(160, 55)
            self.Edit_investor.resize(200, 30)
            self.Edit_password = QLineEdit(self)
            self.Edit_password.move(160, 90)
            self.Edit_password.resize(200, 30)
            self.Edit_addr1 = QLineEdit(self)
            self.Edit_addr1.move(160, 125)
            self.Edit_addr1.resize(200, 30)
            self.Edit_addr2 = QLineEdit(self)
            self.Edit_addr2.move(160, 160)
            self.Edit_addr2.resize(200, 30)
            self.Edit_addr3 = QLineEdit(self)
            self.Edit_addr3.move(160, 195)
            self.Edit_addr3.resize(200, 30)
            self.Edit_APPID = QLineEdit(self)
            self.Edit_APPID.move(160, 230)
            self.Edit_APPID.resize(150, 30)
            self.Edit_authcode = QLineEdit(self)
            self.Edit_authcode.move(160, 265)
            self.Edit_authcode.resize(150, 30)
            self.Edit_auserproductinfo = QLineEdit(self)
            self.Edit_auserproductinfo.move(160, 300)
            self.Edit_auserproductinfo.resize(150, 30)
            self.btn_ok = QPushButton('确认修改账户信息', self)
            self.btn_ok.move(150, 350)
            self.btn_ok.resize(300, 50)
            self.btn_ok.clicked.connect(self.TradeConfirm)
            self.setGeometry(500, 600, 420, 450)
            self.show()
            try:
                global config
                config = configparser.ConfigParser()
                # -read读取ini文件
                config.read('vnctptd.ini', encoding='utf-8')
                brokeid = config.get('setting', 'brokeid')
                investor = config.get('setting', 'investor')
                password = config.get('setting', 'password')
                appid = config.get('setting', 'appid')
                userproductinfo = config.get('setting', 'userproductinfo')
                authcode = config.get('setting', 'authcode')

                print('read %s %s %s' % (investor, password, appid))
                self.Edit_brokerid.setText(brokeid)
                self.Edit_investor.setText(investor)
                self.Edit_password.setText(password)
                self.Edit_APPID.setText(appid)
                self.Edit_authcode.setText(authcode)
                self.Edit_auserproductinfo.setText(userproductinfo)

            except Exception as e:
                print("initUI Error:" + repr(e))

        def TradeConfirm(self):
            global config
            config = configparser.ConfigParser()
            config.read("vnctptd.ini", encoding="utf-8")  # 读取文件
            config.set("setting", "brokeid", self.Edit_brokerid.text())
            config.set("setting", "investor", self.Edit_investor.text())
            config.set("setting", "password", self.Edit_password.text())
            config.set("setting", "appid", self.Edit_APPID.text())
            config.set("setting", "authcode", self.Edit_authcode.text())
            config.set("setting", "userproductinfo", self.Edit_auserproductinfo.text())
            config.set("setting", "address1", self.Edit_addr1.text())
            config.set("setting", "address2", self.Edit_addr2.text())
            config.set("setting", "address3", self.Edit_addr3.text())
            config.write(open("vnctptd.ini", mode="w"))
            messageBox = QMessageBox()
            messageBox.setWindowTitle('提示')
            messageBox.setText('设置成功,\n需重新启动才可生效，确定关闭VNTrader,人工重启VNTrader吗？')
            messageBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            buttonY = messageBox.button(QMessageBox.Yes)
            buttonY.setText('确定')
            buttonN = messageBox.button(QMessageBox.No)
            buttonN.setText('取消')
            reply = messageBox.exec_()
            if messageBox.clickedButton() == buttonY:
                os._exit(1)
            elif messageBox.clickedButton() == buttonN:
                pass

    class DialogTalib(QtWidgets.QDialog):
        class DialogTalibSetting(QtWidgets.QDialog):
            def __init__(self,indicatorsname):
                super().__init__()
                self.indicatorsname = indicatorsname
                self.initUI()
            '''
            def sync_table_double_clicked(self, index):
                column = index.column()
                row = index.row()
                self.indicatorsname = self.tableWidget.item(row, column).text()
                print("table1: " + self.name)
            '''
            def initUI(self):
                self.setWindowIcon(QIcon(r'vnpy.ico'))  # 设置窗口图标
                self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
                self.tableWidget = QTableWidget()
                self.layout = QHBoxLayout()
                self.tableWidget.setRowCount(5)  # 行数
                self.tableWidget.setColumnCount(7)  # 列数
                self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # 所有列自动拉伸，充满界面
                self.tableWidget.setSelectionMode(QAbstractItemView.SingleSelection)  # 设置只能选中一行
                self.tableWidget.setEditTriggers(QTableView.NoEditTriggers)  # 不可编辑
                self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows);  # 设置只有行选中
                self.layout.addWidget(self.tableWidget)
                #self.tableWidget.doubleClicked.connect(self.sync_table_double_clicked)
                self.setWindowTitle(self.indicatorsname + '【'+entry_talib.dict_talibparameter[self.indicatorsname][0][1]+'】')

                parnum = int(entry_talib.dict_talibparameter[self.indicatorsname][0][0])
                parameter = ['','','','','','']
                DEFAULTVALUE = -1
                id=0
                for k in range(parnum):
                    if entry_talib.dict_talibparameter[self.indicatorsname][2][k] != DEFAULTVALUE:
                        parameter[id] = entry_talib.dict_talibparameter[self.indicatorsname][1][k]
                        id = id + 1

                self.tableWidget.setHorizontalHeaderLabels(
                    #['状态','备注',parameter[0], parameter[1], parameter[2], parameter[3], parameter[4], parameter[5],parameter[6]])
                    ['状态', '备注', '参数1', '参数2', '参数3', '参数4', '参数5'])

                '''
                try:
                    print("table111: " + self.indicatorsname)
                    print("table222")
                    print(str(entry_talib.dict_talibparameter))
                    print('查询1'+str(entry_talib.dict_talibparameter[self.indicatorsname]))
                    # 输出：查询1[[0], ['cx1', 'cx2', 'cx3'], [3, 5, 10], [4, 6, 18]]
                    print('查询2'+str(entry_talib.dict_talibparameter[self.indicatorsname][1]))
                    print('查询3 启动状态, ' + str(entry_talib.dict_talibparameter[self.indicatorsname][0][0]))
                    print('查询4 参数组个数 ' +          str(entry_talib.dict_talibparameter[self.indicatorsname][0][1]))
                    # entry_talib.dict_talibparameter[self.indicatorsname][0][0]    [#启动状态 ]
                    # entry_talib.dict_talibparameter[self.indicatorsname][0][1]    [#参数组个数 ]
                    # entry_talib.dict_talibparameter[self.indicatorsname][1][1]    [#参数1, #参数2,..... #参数n]
                    # entry_talib.dict_talibparameter[self.indicatorsname][2]    [参数组1]
                    # entry_talib.dict_talibparameter[self.indicatorsname][3]    [参数组2]
                    # entry_talib.dict_talibparameter[self.indicatorsname][4]    [参数组3]
                except Exception as e:
                    print("initUI Error:" + repr(e))
                '''
                self.setLayout(self.layout)
                #参数个数
                labelpar=[]

                for k in range(parnum):
                    tempparlabel= QLabel(self)
                    tempparlabel.setText(entry_talib.dict_talibparameter[self.indicatorsname][1][k])
                    tempparlabel.move(60, 220+k*40)
                    if entry_talib.dict_talibparameter[self.indicatorsname][2][k]==DEFAULTVALUE:
                        tempparlabel2 = QLabel(self)
                        tempparlabel2.setText('调用数据')
                        tempparlabel2.move(200, 220 + k * 40)
                    else:
                        EditPar = QLineEdit(self)
                        EditPar.setText(str(entry_talib.dict_talibparameter[self.indicatorsname][2][k]))
                        EditPar.move(200, 220+k*40)
                        EditPar.resize(120, 30)
                    labelpar.append(tempparlabel)

                #if entry_talib.dict_talibparameter[self.indicatorsname][3][0]:

                def function_item_clicked(self, QTableWidgetItem):
                    check_state = QTableWidgetItem.checkState()
                    row = QTableWidgetItem.row()
                    if check_state == QtCore.Qt.Checked:
                        if row not in self.delete_row:
                            self.delete_row.append(row)
                    elif check_state == QtCore.Qt.Unchecked:
                        if row in self.delete_row:
                            self.delete_row.remove(row)

                try:
                    for i in range(len(globalvar.dict_talibcondition[self.indicatorsname])):
                        # print('lid: ' + str(globalvar.dict_talibcondition[self.indicatorsname][i]))
                        item = QTableWidgetItem(' 启用该条件')
                        if globalvar.dict_talibcondition[self.indicatorsname][i][1] == 1:
                            item.setCheckState(QtCore.Qt.Checked)
                        else:
                            item.setCheckState(QtCore.Qt.Checked)
                        # item.connect(self.table_algorithmtrading, QtCore.SIGNAL("itemClicked(QTableWidgetItem*)"), self.function_item_clicked)
                        self.tableWidget.setItem(i, 0, item)
                        item = QTableWidgetItem(globalvar.dict_talibcondition[self.indicatorsname][i][2])
                        self.tableWidget.setItem(i, 1, item)
                        item = QTableWidgetItem(globalvar.dict_talibcondition[self.indicatorsname][i][3])
                        self.tableWidget.setItem(i, 2, item)
                        item = QTableWidgetItem(globalvar.dict_talibcondition[self.indicatorsname][i][4])
                        self.tableWidget.setItem(i, 3, item)
                except Exception as e:
                    print("dict_talibcondition Error:" + repr(e))

                try:
                    for i in range(len(entry_talib.dict_talibparameter[self.indicatorsname][3][0])):
                        tempparlabel2 = QLabel(self)
                        EditPar = QLineEdit(self)
                        EditPar2 = QLineEdit(self)
                        tempparlabel2.setText(str(entry_talib.dict_talibparameter[self.indicatorsname][3][0][0]))
                        tempparlabel2.move(60, 230 + parnum * 40)
                        EditPar.setText('>' + str(entry_talib.dict_talibparameter[self.indicatorsname][3][0][1]))
                        EditPar.move(200, 230 + parnum * 40)
                        EditPar.resize(120, 30)
                        EditPar2.setText('趋势条件')
                        EditPar2.move(400, 230 + parnum * 40)
                        EditPar2.resize(120, 30)
                except Exception as e:
                    print("talib.csv格式错误 Error:" + repr(e))
                    return



                '''
                self.btn_authcode = QPushButton('如何获取授权码？', self)
                self.btn_authcode.move(330, 265)
                self.btn_authcode.resize(130, 30)
                #self.btn_authcode.clicked.connect(self.Function_OpenUrl_HOWTOGETAUTHCODE)
                '''

                self.btn_ok = QPushButton('添加指标条件', self)
                self.btn_ok.move(300, 480)
                self.btn_ok.resize(300, 50)
                self.btn_ok.clicked.connect(self.SaveCondition)
                Edit2 = QLineEdit(self)
                Edit2.setText('（该指标条件可用于组合成策略）')
                Edit2.move(360, 550)
                Edit2.resize(180, 30)

                self.setGeometry(500, 600, 420, 450)
                self.show()
                try:
                    global config
                    config = configparser.ConfigParser()
                    # -read读取ini文件
                    config.read('vnctptd.ini', encoding='utf-8')
                    brokeid = config.get('setting', 'brokeid')
                    investor = config.get('setting', 'investor')
                    password = config.get('setting', 'password')
                    appid = config.get('setting', 'appid')
                    userproductinfo = config.get('setting', 'userproductinfo')
                    authcode = config.get('setting', 'authcode')
                    address1 = config.get('setting', 'address1')
                    address2 = config.get('setting', 'address2')
                    address3 = config.get('setting', 'address3')
                    print('read %s %s %s' % (investor, password, appid))
                    self.Edit_brokerid.setText(brokeid)
                    self.Edit_investor.setText(investor)
                    self.Edit_password.setText(password)
                    self.Edit_APPID.setText(appid)
                    self.Edit_authcode.setText(authcode)
                    self.Edit_auserproductinfo.setText(userproductinfo)
                    self.Edit_addr1.setText(address1)
                    self.Edit_addr2.setText(address2)
                    self.Edit_addr3.setText(address3)
                except Exception as e:
                    print("initUI Error:" + repr(e))

            def SaveCondition(self):
                global config
                config = configparser.ConfigParser()
                config.read("vnctptd.ini", encoding="utf-8")  # 读取文件
                config.set("setting", "brokeid", self.Edit_brokerid.text())
                config.set("setting", "investor", self.Edit_investor.text())
                config.set("setting", "password", self.Edit_password.text())
                config.set("setting", "appid", self.Edit_APPID.text())
                config.set("setting", "authcode", self.Edit_authcode.text())
                config.set("setting", "userproductinfo", self.Edit_auserproductinfo.text())
                config.set("setting", "address1", self.Edit_addr1.text())
                config.set("setting", "address2", self.Edit_addr2.text())
                config.set("setting", "address3", self.Edit_addr3.text())
                config.write(open("vnctptd.ini", mode="w"))
                


                messageBox = QMessageBox()
                messageBox.setWindowTitle('提示')
                messageBox.setText('设置成功,\n需重新启动才可生效，确定关闭VNTrader,人工重启VNTrader吗？')
                messageBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
                buttonY = messageBox.button(QMessageBox.Yes)
                buttonY.setText('确定')
                buttonN = messageBox.button(QMessageBox.No)
                buttonN.setText('取消')
                reply = messageBox.exec_()

                strlist= [self.indicatorsname,0,"","",""]
                try:
                    if len(globalvar.dict_talibcondition[self.indicatorsname]) == 0:
                        pass
                except Exception as e:
                    globalvar.dict_talibcondition[self.indicatorsname] = []
                    print("Function_Buttonclicke0 Error:" + repr(e))
                globalvar.dict_talibcondition[self.indicatorsname].append(strlist)

                #if messageBox.clickedButton() == buttonY:
                #    os._exit(1)
                #elif messageBox.clickedButton() == buttonN:
                #    pass

            def showDialog(self):
                text, ok = QInputDialog.getText(self, '选择期货公司自动确认brokeid和ip',
                                                '选择期货公司:')
                if ok:
                    self.le.setText(str(text))

        def __init__(self):
            super().__init__()
            self.initUI()

        def closeEvent(self, event):
            globalvar.DialogTalibState=False
            try:
                if self.dlg_talibindicatrixsetting:
                    self.dlg_talibindicatrixsetting.close()
            except Exception as e:
                print("DialogTalib closeEvent Error:" + repr(e))

        def sync_table_double_clicked(self, index):
            column = index.column()
            row = index.row()
            # current_item = self.tableWidget.item(row, column)
            # current_widget = self.tableWidget.cellWidget(row, column)
            # 取Talib指标名
            strs = self.tableWidget.item(row, column).text()
            print("table: " + strs)
            self.dlg_talibindicatrixsetting = self.DialogTalibSetting(strs)
            self.dlg_talibindicatrixsetting.show()
            self.dlg_talibindicatrixsetting.resize(900, 620)
            # 居中窗口
            screen = QDesktopWidget().screenGeometry()
            size = self.dlg_talibindicatrixsetting.geometry()
            self.dlg_talibindicatrixsetting.move((screen.width() - size.width()) / 2,
                                     (screen.height() - size.height()) / 2)
            self.dlg_talibindicatrixsetting.exec_()

        def initUI(self):
            self.setWindowIcon(QIcon(r'vnpy.ico'))  # 设置窗口图标
            self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
            self.tableWidget = QTableWidget()
            self.layout = QHBoxLayout()
            # self.resize(1400, 900)
            # tableWidget = QTableWidget()
            self.tableWidget.setRowCount(200)  # 行数
            self.tableWidget.setColumnCount(5)  # 列数
            self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # 所有列自动拉伸，充满界面
            # tableWidget.setSelectionMode(QAbstractItemView.SingleSelection)  # 设置只能选中一行
            self.tableWidget.setEditTriggers(QTableView.NoEditTriggers)  # 不可编辑
            # tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows);  # 设置只有行选中
            self.layout.addWidget(self.tableWidget)
            # self.connect(tableWidget,  itemClicked, this, & DialogTalib::enter);

            self.tableWidget.doubleClicked.connect(self.sync_table_double_clicked)

            self.tableWidget.setHorizontalHeaderLabels(
                ['Talib指标列表', '【TALIB指标正在', '开发集成中，', '请耐心等待】', '', '',
                 ''])  # 横向标题排列，如果使用setVerticalHeaderLabels则是纵向排列标题


            # 输出Talib支持所有的函数
            '''
            li = ta.get_functions()
            for i in range(len(li)):
                item = QTableWidgetItem(str(li[i]))
                self.tableWidget.setItem(0, i, item)
                
            '''
            dict_talibgroup = ta.get_function_groups()
            '''
            try:
                print("talib 0: " + dict_talibgroup['Cycle Indicators'][0])
                print("talib 1: " + dict_talibgroup['Cycle Indicators'][1])
                print("talib 2: " + dict_talibgroup['Cycle Indicators'][2])
                print("talib 3: " + dict_talibgroup['Cycle Indicators'][3])
            except Exception as e:
                print("talib Error:" + repr(e))
            '''
            '''
            for i, v in enumerate(dict_talibgroup):
                print(str('type: '),i, str(v))
                for j in range(len(dict_talibgroup[str(v)])):
                    print("  名称：" + dict_talibgroup[str(v)][j])
            '''

            dict_talibIndicatorstype = {'Cycle Indicators': '周期指标', 'Math Operators': '数学运算符', 'Math Transform': '数学变换',
                                        'Momentum Indicators': '动量指标', 'Overlap Studies': '重叠指标',
                                        'Pattern Recognition': 'K线形态识别', 'Price Transform': '价格指标',
                                        'Statistic Functions': '统计学指标', 'Volatility Indicators': '波动性指标',
                                        'Volume Indicators': '成交量指标'}
            dict_talibIndicatorShow = {'Cycle Indicators': True, 'Math Operators': True, 'Math Transform': True,
                                       'Momentum Indicators': False, 'Overlap Studies': False,
                                       'Pattern Recognition': False, 'Price Transform': True,
                                       'Statistic Functions': True, 'Volatility Indicators': False,
                                       'Volume Indicators': False}

            item = QTableWidgetItem('双击单元格，设置指标自动交易')
            self.tableWidget.setItem(0, 0, item)

            k = 1
            for i, v in enumerate(dict_talibgroup):
                try:
                    if dict_talibIndicatorShow[str(v)]:
                        continue
                except Exception as e:
                    print("dict_talibIndicatorShow :" + repr(e))

                item = QTableWidgetItem('【' + str(v) + dict_talibIndicatorstype[str(v)] + '】')
                self.tableWidget.setItem(k, 0, item)
                k = k + 1
                for j in range(len(dict_talibgroup[str(v)])):
                    # print("  名称：" + dict_talibgroup[str(v)][j])
                    item = QTableWidgetItem(dict_talibgroup[str(v)][j])
                    self.tableWidget.setItem(k, j, item)
                k = k + len(dict_talibgroup[str(v)]) / 5 + 2

            # 输出Talib支持所有的函数
            # li2 = ta.get_function_groups()
            # for j in range(len(li2)):
            #    print(str(li2[j]))
            # print ('get_function_groups'+ str(ta.get_function_groups()))

            self.setLayout(self.layout)

            return
            self.setWindowFlags(Qt.WindowCloseButtonHint)
            # self.btn_helper = QPushButton('选择期货公司', self)
            # self.btn_helper.move(380, 20)
            # self.btn_helper.clicked.connect(self.showDialog)
            # self.table_strategy = QtWidgets.QTableWidget(self.tab_strategy)
            self.table_strategy = QtWidgets.QTableWidget()
            self.table_strategy.setObjectName("table_strategy")
            self.table_strategy.verticalHeader().setVisible(False)  # 隐藏垂直表头
            self.table_strategy.horizontalHeader().setVisible(True)  # 隐藏水平表头
            self.table_strategy.setColumnCount(9)
            self.table_strategy.setRowCount(0)
            self.table_strategy.setEditTriggers(self.table_strategy.NoEditTriggers)
            self.table_strategy.setHorizontalHeaderLabels(
                ['ID(勾选执行)', '策略名称', '策略文件名称(双击编辑，仅限英文名)', '胜率', '盈亏比', '今日交易', '合约设置', '回测', '查看策略仓位'])  # 设置表头文字
            # self.table_strategy.doubleClicked.connect(self.Function_doubleClicked_strategy)
            self.table_strategy.setColumnWidth(2, 220)
            self.table_strategy.setRowHeight(0, 35)
            Trade_InstrumentBtn = QtWidgets.QPushButton('合约设置')
            Trade_InstrumentBtn.setFlat(True)
            Trade_InstrumentBtn.setStyleSheet('background-color:#ff0000;')
            # searchBtn.setDown(True)
            Trade_InstrumentBtn.setStyleSheet('QPushButton{margin:3px}')
            self.table_strategy.setCellWidget(0, 6, Trade_InstrumentBtn)
            Trade_BacktestingBtn = QtWidgets.QPushButton('回测')
            Trade_BacktestingBtn.setFlat(True)
            Trade_BacktestingBtn.setStyleSheet('background-color:#ff0000;')
            # searchBtn.setDown(True)
            Trade_BacktestingBtn.setStyleSheet('QPushButton{margin:3px}')
            self.table_strategy.setCellWidget(0, 7, Trade_BacktestingBtn)
            Trade_BacktestingBtn = QtWidgets.QPushButton('查看策略仓位')
            Trade_BacktestingBtn.setFlat(True)
            Trade_BacktestingBtn.setStyleSheet('background-color:#ff0000;')
            # searchBtn.setDown(True)
            Trade_BacktestingBtn.setStyleSheet('QPushButton{margin:3px}')
            # self.table_strategy.setCellWidget(0, 8, Trade_BacktestingBtn)
            # self.gridLayout_strategy.addWidget(self.table_strategy, 0, 0, 2, 2)
            # self.gridLayout_strategy.addWidget(self.Button_AddStrategy, 1, 0, 1, 1)
            # self.gridLayout_strategy.addWidget(self.Button_OpenStrategyPath, 1, 1, 1, 1)
            # self.gridLayout_account.addWidget(self.table_account, 0, 0, 2, 2)
            # self.gridLayout_account.addWidget(self.Button_AddInvestor, 1, 0, 1, 1)
            # self.gridLayout_account.addWidget(self.Button_ModifyInvestor, 1, 1, 1, 1)
            # self.gridLayout_account.addWidget(self.Button_Kaihu, 2, 0, 1, 1)
            # self.gridLayout_account.addWidget(self.Button_Simnow, 2, 1, 1, 1)

            return
            self.label_1 = QLabel(self)
            self.label_1.setText("期货公司编码")
            self.label_1.move(60, 20)
            self.label_2 = QLabel(self)
            self.label_2.setText("交易账户")
            self.label_2.move(60, 55)
            self.label_3 = QLabel(self)
            self.label_3.setText("交易密码")
            self.label_3.move(60, 90)
            self.label_4 = QLabel(self)
            self.label_4.setText("交易服务器1")
            self.label_4.move(60, 125)
            self.label_5 = QLabel(self)
            self.label_5.setText("交易服务器2")
            self.label_5.move(60, 160)
            self.label_6 = QLabel(self)
            self.label_6.setText("交易服务器3")
            self.label_6.move(60, 195)
            self.label_7 = QLabel(self)
            self.label_7.setText("输入格式 tcp://ip:port")
            self.label_7.resize(140, 30)
            self.label_7.move(380, 230)
            self.label_8 = QLabel(self)
            self.label_8.setText("APPID")
            self.label_8.move(60, 230)
            self.label_9 = QLabel(self)
            self.label_9.setText("AUTHCODE")
            self.label_9.move(60, 265)
            self.label_10 = QLabel(self)
            self.label_10.setText("ProductInfo")
            self.label_10.move(60, 300)
            self.btn_authcode = QPushButton('如何获取授权码？', self)
            self.btn_authcode.move(330, 265)
            self.btn_authcode.resize(130, 30)
            self.btn_authcode.clicked.connect(self.Function_OpenUrl_HOWTOGETAUTHCODE)
            self.Edit_brokerid = QLineEdit(self)
            self.Edit_brokerid.move(160, 20)
            self.Edit_brokerid.resize(200, 30)
            self.Edit_investor = QLineEdit(self)
            self.Edit_investor.move(160, 55)
            self.Edit_investor.resize(200, 30)
            self.Edit_password = QLineEdit(self)
            self.Edit_password.move(160, 90)
            self.Edit_password.resize(200, 30)
            self.Edit_addr1 = QLineEdit(self)
            self.Edit_addr1.move(160, 125)
            self.Edit_addr1.resize(200, 30)
            self.Edit_addr2 = QLineEdit(self)
            self.Edit_addr2.move(160, 160)
            self.Edit_addr2.resize(200, 30)
            self.Edit_addr3 = QLineEdit(self)
            self.Edit_addr3.move(160, 195)
            self.Edit_addr3.resize(200, 30)
            self.Edit_APPID = QLineEdit(self)
            self.Edit_APPID.move(160, 230)
            self.Edit_APPID.resize(150, 30)
            self.Edit_authcode = QLineEdit(self)
            self.Edit_authcode.move(160, 265)
            self.Edit_authcode.resize(150, 30)
            self.Edit_auserproductinfo = QLineEdit(self)
            self.Edit_auserproductinfo.move(160, 300)
            self.Edit_auserproductinfo.resize(150, 30)
            self.btn_ok = QPushButton('确认修改账户信息', self)
            self.btn_ok.move(150, 350)
            self.btn_ok.resize(300, 50)
            self.btn_ok.clicked.connect(self.SaveInvestor)
            self.setGeometry(500, 600, 420, 450)
            self.show()
            try:
                global config
                config = configparser.ConfigParser()
                # -read读取ini文件
                config.read('vnctptd.ini', encoding='utf-8')
                brokeid = config.get('setting', 'brokeid')
                investor = config.get('setting', 'investor')
                password = config.get('setting', 'password')
                appid = config.get('setting', 'appid')
                userproductinfo = config.get('setting', 'userproductinfo')
                authcode = config.get('setting', 'authcode')
                address1 = config.get('setting', 'address1')
                address2 = config.get('setting', 'address2')
                address3 = config.get('setting', 'address3')
                print('read %s %s %s' % (investor, password, appid))
                self.Edit_brokerid.setText(brokeid)
                self.Edit_investor.setText(investor)
                self.Edit_password.setText(password)
                self.Edit_APPID.setText(appid)
                self.Edit_authcode.setText(authcode)
                self.Edit_auserproductinfo.setText(userproductinfo)
                self.Edit_addr1.setText(address1)
                self.Edit_addr2.setText(address2)
                self.Edit_addr3.setText(address3)
            except Exception as e:
                print("initUI Error:" + repr(e))

        def SaveInvestor(self):
            global config
            config = configparser.ConfigParser()
            config.read("vnctptd.ini", encoding="utf-8")  # 读取文件
            config.set("setting", "brokeid", self.Edit_brokerid.text())
            config.set("setting", "investor", self.Edit_investor.text())
            config.set("setting", "password", self.Edit_password.text())
            config.set("setting", "appid", self.Edit_APPID.text())
            config.set("setting", "authcode", self.Edit_authcode.text())
            config.set("setting", "userproductinfo", self.Edit_auserproductinfo.text())
            config.set("setting", "address1", self.Edit_addr1.text())
            config.set("setting", "address2", self.Edit_addr2.text())
            config.set("setting", "address3", self.Edit_addr3.text())
            config.write(open("vnctptd.ini", mode="w"))
            messageBox = QMessageBox()
            messageBox.setWindowTitle('提示')
            messageBox.setText('设置成功,\n需重新启动才可生效，确定关闭VNTrader,人工重启VNTrader吗？')
            messageBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            buttonY = messageBox.button(QMessageBox.Yes)
            buttonY.setText('确定')
            buttonN = messageBox.button(QMessageBox.No)
            buttonN.setText('取消')
            reply = messageBox.exec_()
            if messageBox.clickedButton() == buttonY:
                os._exit(1)
            elif messageBox.clickedButton() == buttonN:
                pass

        def showDialog(self):
            text, ok = QInputDialog.getText(self, '选择期货公司自动确认brokeid和ip',
                                            '选择期货公司:')
            if ok:
                self.le.setText(str(text))

    class DialogInvestor(QtWidgets.QDialog):
        def __init__(self):
            super().__init__()
            self.initUI()

        def closeEvent(self, event):
            """
            重写closeEvent方法，实现dialog窗体关闭时执行一些代码
            :param event: close()触发的事件
            :return: None
            """
            # .button(QMessageBox::Yes)->setText("是");
            messagebox = QMessageBox()
            messagebox.setWindowTitle('提示')
            messagebox.setText('是否关闭窗口？')
            messagebox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            buttonY = messagebox.button(QMessageBox.Yes)
            buttonY.setText('确定')
            buttonN = messagebox.button(QMessageBox.No)
            buttonN.setText('取消')
            reply = messagebox.exec_()
            if messagebox.clickedButton() == buttonY:
                event.accept()
            elif messagebox.clickedButton() == buttonN:
                event.ignore()

        def Function_OpenUrl_HOWTOGETAUTHCODE(self):
            webbrowser.open('http://www.vnpy.cn/')

        def initUI(self):
            self.setWindowFlags(Qt.WindowCloseButtonHint)
            # self.btn_helper = QPushButton('选择期货公司', self)
            # self.btn_helper.move(380, 20)
            # self.btn_helper.clicked.connect(self.showDialog)
            self.label_1 = QLabel(self)
            self.label_1.setText("期货公司编码")
            self.label_1.move(60, 20)
            self.label_2 = QLabel(self)
            self.label_2.setText("交易账户")
            self.label_2.move(60, 55)
            self.label_3 = QLabel(self)
            self.label_3.setText("交易密码")
            self.label_3.move(60, 90)
            self.label_4 = QLabel(self)
            self.label_4.setText("交易服务器1")
            self.label_4.move(60, 125)
            self.label_5 = QLabel(self)
            self.label_5.setText("交易服务器2")
            self.label_5.move(60, 160)
            self.label_6 = QLabel(self)
            self.label_6.setText("交易服务器3")
            self.label_6.move(60, 195)
            self.label_7 = QLabel(self)
            self.label_7.setText("输入格式 tcp://ip:port")
            self.label_7.resize(140, 30)
            self.label_7.move(380, 230)
            self.label_8 = QLabel(self)
            self.label_8.setText("APPID")
            self.label_8.move(60, 230)
            self.label_9 = QLabel(self)
            self.label_9.setText("AUTHCODE")
            self.label_9.move(60, 265)
            self.label_10 = QLabel(self)
            self.label_10.setText("ProductInfo")
            self.label_10.move(60, 300)
            self.btn_authcode = QPushButton('如何获取授权码？', self)
            self.btn_authcode.move(330, 265)
            self.btn_authcode.resize(130, 30)
            self.btn_authcode.clicked.connect(self.Function_OpenUrl_HOWTOGETAUTHCODE)
            self.Edit_brokerid = QLineEdit(self)
            self.Edit_brokerid.move(160, 20)
            self.Edit_brokerid.resize(200, 30)
            self.Edit_investor = QLineEdit(self)
            self.Edit_investor.move(160, 55)
            self.Edit_investor.resize(200, 30)
            self.Edit_password = QLineEdit(self)
            self.Edit_password.move(160, 90)
            self.Edit_password.resize(200, 30)
            self.Edit_addr1 = QLineEdit(self)
            self.Edit_addr1.move(160, 125)
            self.Edit_addr1.resize(200, 30)
            self.Edit_addr2 = QLineEdit(self)
            self.Edit_addr2.move(160, 160)
            self.Edit_addr2.resize(200, 30)
            self.Edit_addr3 = QLineEdit(self)
            self.Edit_addr3.move(160, 195)
            self.Edit_addr3.resize(200, 30)
            self.Edit_APPID = QLineEdit(self)
            self.Edit_APPID.move(160, 230)
            self.Edit_APPID.resize(150, 30)
            self.Edit_authcode = QLineEdit(self)
            self.Edit_authcode.move(160, 265)
            self.Edit_authcode.resize(150, 30)
            self.Edit_auserproductinfo = QLineEdit(self)
            self.Edit_auserproductinfo.move(160, 300)
            self.Edit_auserproductinfo.resize(150, 30)
            self.btn_ok = QPushButton('确认修改账户信息', self)
            self.btn_ok.move(150, 350)
            self.btn_ok.resize(300, 50)
            self.btn_ok.clicked.connect(self.SaveInvestor)
            self.setGeometry(500, 600, 420, 450)
            self.show()
            try:
                global config
                config = configparser.ConfigParser()
                # -read读取ini文件
                config.read('vnctptd.ini', encoding='utf-8')
                brokeid = config.get('setting', 'brokeid')
                investor = config.get('setting', 'investor')
                password = config.get('setting', 'password')
                appid = config.get('setting', 'appid')
                userproductinfo = config.get('setting', 'userproductinfo')
                authcode = config.get('setting', 'authcode')
                address1 = config.get('setting', 'address1')
                address2 = config.get('setting', 'address2')
                address3 = config.get('setting', 'address3')
                print('read %s %s %s' % (investor, password, appid))
                self.Edit_brokerid.setText(brokeid)
                self.Edit_investor.setText(investor)
                self.Edit_password.setText(password)
                self.Edit_APPID.setText(appid)
                self.Edit_authcode.setText(authcode)
                self.Edit_auserproductinfo.setText(userproductinfo)
                self.Edit_addr1.setText(address1)
                self.Edit_addr2.setText(address2)
                self.Edit_addr3.setText(address3)
            except Exception as e:
                print("initUI Error:" + repr(e))

        def SaveInvestor(self):
            global config
            config = configparser.ConfigParser()
            config.read("vnctptd.ini", encoding="utf-8")  # 读取文件
            config.set("setting", "brokeid", self.Edit_brokerid.text())
            config.set("setting", "investor", self.Edit_investor.text())
            config.set("setting", "password", self.Edit_password.text())
            config.set("setting", "appid", self.Edit_APPID.text())
            config.set("setting", "authcode", self.Edit_authcode.text())
            config.set("setting", "userproductinfo", self.Edit_auserproductinfo.text())
            config.set("setting", "address1", self.Edit_addr1.text())
            config.set("setting", "address2", self.Edit_addr2.text())
            config.set("setting", "address3", self.Edit_addr3.text())
            config.write(open("vnctptd.ini", mode="w"))
            messageBox = QMessageBox()
            messageBox.setWindowTitle('提示')
            messageBox.setText('设置成功,\n需重新启动才可生效，确定关闭VNTrader,人工重启VNTrader吗？')
            messageBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            buttonY = messageBox.button(QMessageBox.Yes)
            buttonY.setText('确定')
            buttonN = messageBox.button(QMessageBox.No)
            buttonN.setText('取消')
            reply = messageBox.exec_()
            if messageBox.clickedButton() == buttonY:
                os._exit(1)
            elif messageBox.clickedButton() == buttonN:
                pass

        def showDialog(self):
            text, ok = QInputDialog.getText(self, '选择期货公司自动确认brokeid和ip',
                                            '选择期货公司:')
            if ok:
                self.le.setText(str(text))

    class DialogCapitalCurve(QMainWindow):
        def __init__(self):
            super().__init__()
            self.initUI()

        def Function_OpenUrl_HOWTOGETAUTHCODE(self):
            webbrowser.open('http://www.vnpy.cn/')

        def initUI(self):
            self.setWindowFlags(Qt.WindowCloseButtonHint)

            self.btn_helper = QPushButton('选择期货公司', self)
            self.btn_helper.move(300, 20)
            self.btn_helper.clicked.connect(self.showDialog)

            self.label_1 = QLabel(self)
            self.label_1.setText("期货公司编码")
            self.label_1.move(60, 20)

            self.label_2 = QLabel(self)
            self.label_2.setText("交易账户")
            self.label_2.move(60, 55)

            self.label_3 = QLabel(self)
            self.label_3.setText("交易密码")
            self.label_3.move(60, 90)

            self.label_4 = QLabel(self)
            self.label_4.setText("交易服务器")
            self.label_4.move(60, 125)

            self.label_4b = QLabel(self)
            self.label_4b.setText("输入格式 tcp://ip:port")
            self.label_4b.resize(140, 30)
            self.label_4b.move(300, 125)

            self.label_5 = QLabel(self)
            self.label_5.setText("APPID")
            self.label_5.move(60, 160)

            self.label_6 = QLabel(self)
            self.label_6.setText("AUTHCODE")
            self.label_6.move(60, 195)

            self.btn_authcode = QPushButton('如何获取授权码？', self)
            self.btn_authcode.move(300, 195)
            self.btn_authcode.resize(130, 30)
            self.btn_authcode.clicked.connect(self.Function_OpenUrl_HOWTOGETAUTHCODE)

            self.Edit_brokerid = QLineEdit(self)
            self.Edit_brokerid.move(140, 20)
            self.Edit_brokerid.resize(150, 30)

            self.Edit_investor = QLineEdit(self)
            self.Edit_investor.move(140, 55)
            self.Edit_investor.resize(150, 30)

            self.Edit_password = QLineEdit(self)
            self.Edit_password.move(140, 90)
            self.Edit_password.resize(150, 30)

            self.Edit_addr = QLineEdit(self)
            self.Edit_addr.move(140, 125)
            self.Edit_addr.resize(150, 30)

            self.Edit_APPID = QLineEdit(self)
            self.Edit_APPID.move(140, 160)
            self.Edit_APPID.resize(150, 30)

            self.Edit_authcode = QLineEdit(self)
            self.Edit_authcode.move(140, 195)
            self.Edit_authcode.resize(150, 30)

            self.btn_ok = QPushButton('确认添加该账户', self)
            self.btn_ok.move(170, 250)
            # self.btn.clicked.connect(self.showDialog)
            self.btn_ok.clicked.connect(self.showDialog)
            self.setGeometry(300, 300, 290, 150)
            self.show()

        def showDialog(self):
            text, ok = QInputDialog.getText(self, '选择期货公司自动确认brokeid和ip',
                                            '选择期货公司:')

            if ok:
                self.le.setText(str(text))

    def OnStart(self):
        # tradestate = 0
        # backteststate = 0
        if backteststate == 0:
            globalvar.tradestate = 1
            self.Button_Start.setEnabled(False)
            self.Button_Stop.setEnabled(True)
        else:
            self.autologoutwarnwin = QMessageBox(None)
            self.autologoutwarnwin.setIcon(QMessageBox.Warning)
            self.autologoutwarnwin.setText(('实盘交易前，请先停止回测'))
            self.autologoutwarnwin.setWindowTitle(('说明'))
            self.autologoutwarnwin.setStandardButtons(QMessageBox.Ok)
            # self.buttonOK = self.autologoutwarnwin.button(QMessageBox.Ok)
            # self.buttonOK.setText('我知道了,打开上期SIMNOW网站')
            # self.autologoutwarnwin.buttonClicked.connect(self.autologoutwarn_accepted)
            self.autologoutwarnwin.exec_()
            # webbrowser.open('http://www.simnow.com.cn/')

    def OnStop(self):
        globalvar.tradestate = 0
        self.Button_Start.setEnabled(True)
        self.Button_Stop.setEnabled(False)

    # global logname
    # logname = u'20210601'

    def ClearPath(self, path):
        ls = os.listdir(path)
        for i in ls:
            c_path = os.path.join(path, i)
            if os.path.isdir(c_path):
                print(c_path)
                self.ClearPath(c_path)
            else:
                file = os.path.splitext(c_path)
                filename, type = file
                if type == ".txt":
                    os.remove(c_path)
                    print("Delete file complete :", c_path)

    def Function_ClearMdLog(self):
        self.ClearPath("log/md")

    def Function_ClearTdLog(self):
        self.ClearPath("log/td")

    # 打开资金曲线对话框
    def Function_OpenCapitalCurve(self):
        ui_demo = self.DialogCapitalCurve()
        ui_demo.centralWidget()
        # 居中窗口
        screen = QDesktopWidget().screenGeometry()
        size = ui_demo.geometry()
        ui_demo.move((screen.width() - size.width()) / 2 - 75,
                     (screen.height() - size.height()) / 2 - 50)
        ui_demo.setWindowTitle('添加交易账户')
        ui_demo.show()
        ui_demo.resize(450, 300)
        # self.childwidget = self.childwidget(self)
        # self.childwidget.exec_()
        ui_demo.exec_()

    # 策略说明
    def Function_StrategyInstructions(self):
        webbrowser.open('https://zhuanlan.zhihu.com/p/393090084')

    # 双击下单
    def Function_doubleClicked_TradeConfirm(self):
        ui_demo = self.DialogTradeConfirm()
        # ui_demo.centralWidget()
        # 居中窗口
        screen = QDesktopWidget().screenGeometry()
        size = ui_demo.geometry()
        ui_demo.move((screen.width() - size.width()) / 2 - 75,
                     (screen.height() - size.height()) / 2 - 10)
        ui_demo.setWindowTitle('下单确认')
        ui_demo.show()
        ui_demo.resize(600, 440)
        # self.childwidget = self.childwidget(self)
        ui_demo.exec_()

    # 添加账户
    def Function_AddInvestor(self):
        ui_demo = self.DialogInvestor()
        # ui_demo.centralWidget()
        # 居中窗口
        screen = QDesktopWidget().screenGeometry()
        size = ui_demo.geometry()
        ui_demo.move((screen.width() - size.width()) / 2 - 75,
                     (screen.height() - size.height()) / 2 - 10)
        ui_demo.setWindowTitle('添加交易账户')
        ui_demo.show()
        ui_demo.resize(600, 440)
        # self.childwidget = self.childwidget(self)
        ui_demo.exec_()

    # 修改账户
    def Function_ModifyInvestor(self):
        webbrowser.open('https://zhuanlan.zhihu.com/p/382856586')
        '''
        ui_demo = self.DialogInvestor()
        # 居中窗口
        screen = QDesktopWidget().screenGeometry()
        size = ui_demo.geometry()
        ui_demo.move((screen.width() - size.width()) / 2 -75,
                  (screen.height() - size.height()) / 2  -50)
        ui_demo.setWindowTitle('修改交易账户')
        ui_demo.show()
        ui_demo.resize(450, 300)
        self.childwidget = self.childwidget(self)
        self.childwidget.exec_()
        '''

    def Function_OpenLog_TD(self):
        import subprocess as sp
        programName = "notepad.exe"
        fileName = "log//td//" + '2021' + ".txt"
        sp.Popen([programName, fileName])

    def Function_OpenLog_MD(self):
        import subprocess as sp
        programName = "notepad.exe"
        fileName = "log//md//" + '2021' + ".txt"
        sp.Popen([programName, fileName])

    def Function_OpenUrl_SIMNOW(self):
        # QtWidgets.QMessageBox.warning(self, "Warning", "输入数据错误，请重新输入！",QMessageBox.Yes)
        self.autologoutwarnwin = QMessageBox(None)
        self.autologoutwarnwin.setIcon(QMessageBox.Warning)
        self.autologoutwarnwin.setText(('上期SIMNOW官网提供CTP模拟账户注册，\n网站只能在工作日白天才能访问。\n\n但模拟交易账户注册成功后，\n和实盘账户交易时间是一致的。'))
        self.autologoutwarnwin.setWindowTitle(('说明'))
        self.autologoutwarnwin.setStandardButtons(QMessageBox.Ok)
        self.buttonOK = self.autologoutwarnwin.button(QMessageBox.Ok)
        self.buttonOK.setText('我知道了,打开上期SIMNOW网站')
        # self.autologoutwarnwin.buttonClicked.connect(self.autologoutwarn_accepted)
        self.autologoutwarnwin.exec_()
        webbrowser.open('http://www.simnow.com.cn/')

    def Function_OpenUrl_VNPY(self):
        webbrowser.open('http://www.vnpy.cn/')

    def Function_OpenUrl_VNTRADER(self):
        webbrowser.open('http://www.vntrader.cn/')

    def Function_OpenUrl_ZHIHU(self):
        webbrowser.open('https://www.zhihu.com/org/vnpy/posts')

    def Function_OpenUrl_ZHIHUVIDEO(self):
        webbrowser.open('https://www.zhihu.com/org/vnpy/zvideos/')

    def Function_OpenUrl_COOLQUANT(self):
        webbrowser.open('http://www.coolquant.cn/')

    def Function_OpenUrl_KAIHU(self):
        webbrowser.open('http://www.kaihucn.cn/')

    def Function_OpenUrl_Plus(self):
        webbrowser.open('http://www.vnpy.cn/qplus.html')

    def Function_OpenUrl_Community(self):
        webbrowser.open('http://q.vnpy.cn/')

    def Function_OpenUrl_BandPlus(self):
        webbrowser.open('http://q.vnpy.cn/')

    def Function_OpenUrl_Buyplus(self):
        webbrowser.open('http://q.vnpy.cn/')

    def Function_FaqKAIHU(self):
        webbrowser.open('https://www.zhihu.com/zvideo/1333746770867236864')

    def Function_OpenDllLog(self):
        self.Button_OpenDll.setChecked(True)
        self.Button_CloseDll.setChecked(False)
        global td, md
        globalvar.md.OpenLog()
        globalvar.td.OpenLog()

    def Function_CloseDllLog(self):
        self.Button_OpenDll.setChecked(False)
        self.Button_CloseDll.setChecked(True)
        global td, md
        globalvar.md.CloseLog()
        globalvar.td.CloseLog()

    def Function_EnableStrategyManage_SingleThread(self):
        self.Button_StrategyManage_SingleThread.setChecked(True)
        self.Button_StrategyManage_MulitProcess.setChecked(False)

    def Function_EnableStrategyManage_MulitProcess(self):
        self.Button_StrategyManage_SingleThread.setChecked(True)
        self.Button_StrategyManage_MulitProcess.setChecked(False)

    def Function_KlineSource_RealTimeTick(self):
        self.Button_KlineSource_RealTimeTick.setChecked(True)
        self.Button_KlineSource_ServerToday.setChecked(False)
        self.Button_KlineSource_ServerMultiday.setChecked(False)
        globalvar.klineserverstate = 0

    def Function_KlineSource_ServerToday(self):
        self.Button_KlineSource_RealTimeTick.setChecked(False)
        self.Button_KlineSource_ServerToday.setChecked(True)
        self.Button_KlineSource_ServerMultiday.setChecked(False)
        globalvar.klineserverstate = 1
        self.GetKlineFromeServer()

    def Function_KlineSource_ServerMultiday(self):
        self.Button_KlineSource_RealTimeTick.setChecked(False)
        self.Button_KlineSource_ServerToday.setChecked(False)
        self.Button_KlineSource_ServerMultiday.setChecked(True)
        globalvar.klineserverstate = 2
        self.GetKlineFromeServer()

    def Function_FaqDevelopmentEnvironment(self):
        webbrowser.open('https://www.zhihu.com/zvideo/1333746770867236864')

    def Function_doubleClicked_algorithmtrading_limit(self):
        """
         作用：双击事件监听，显示被选中的单元格
        """
        # 打印被选中的单元格
        for i in self.table_algorithmtrading.selectedItems():
            print(i.row(), i.column(), i.text())
            # self.setWindowTitle(i.text())

    def Function_doubleClicked_Trade(self):
        """
         作用：双击事件监听，显示被选中的单元格
        """
        # 打印被选中的单元格
        for i in self.table_account.selectedItems():
            print(i.row(), i.column(), i.text())
            # self.setWindowTitle(i.text())

    def Function_doubleClicked_strategy(self):
        """
        作用：双击事件监听，用默认方式打开文件
        """
        for i in self.table_strategy.selectedItems():
            # print(i.row(), i.column(), i.text())
            print(i.text())
            os.system(i.text())

    # 双击打开历史交易日志
    def Function_doubleClicked_historytd(self):
        """
        作用：双击事件监听，用默认方式打开文件
        """
        for i in self.table_historytd.selectedItems():
            # print(i.row(), i.column(), i.text())
            print(i.text())
            os.system(i.text())

    # 双击打开历史行情日志
    def Function_doubleClicked_historymd(self):
        """
        作用：双击事件监听，用默认方式打开文件
        """
        for i in self.table_historymd.selectedItems():
            # print(i.row(), i.column(), i.text())
            print(i.text())
            os.system(i.text())

    def Function_Buttonclickh1(self):
        try:
            if '最近访问' in self.Button_h[0].text():
                return
            else:
                self.change_comboBox(self.Button_h[0].text())
        except Exception as e:
            print("Function_Buttonclickh1:" + repr(e))

    def Function_Buttonclickh2(self):
        try:
            if '最近访问' in self.Button_h[1].text():
                return
            else:
                self.change_comboBox(self.Button_h[1].text())
        except Exception as e:
            print("Function_Buttonclickh2:" + repr(e))

    def Function_Buttonclickh3(self):
        try:
            if '最近访问' in self.Button_h[2].text():
                return
            else:
                self.change_comboBox(self.Button_h[2].text())
        except Exception as e:
            print("Function_Buttonclickh3:" + repr(e))

    def Function_Buttonclickh4(self):
        try:
            if '最近访问' in self.Button_h[3].text():
                return
            else:
                self.change_comboBox(self.Button_h[3].text())
        except Exception as e:
            print("Function_Buttonclickh4:" + repr(e))

    def Function_Buttonclickh5(self):
        try:
            if '最近访问' in self.Button_h[4].text():
                return
            else:
                self.change_comboBox(self.Button_h[4].text())
        except Exception as e:
            print("Function_Buttonclickh5:" + repr(e))

    def Function_Buttonclickh6(self):
        try:
            if '最近访问' in self.Button_h[5].text():
                return
            else:
                self.change_comboBox(self.Button_h[5].text())
        except Exception as e:
            print("Function_Buttonclickh6:" + repr(e))

    def Function_Buttonclickh7(self):
        try:
            if '最近访问' in self.Button_h[6].text():
                return
            else:
                self.change_comboBox(self.Button_h[6].text())
        except Exception as e:
            print("Function_Buttonclickh7:" + repr(e))

    def Function_Buttonclickh8(self):
        try:
            if '最近访问' in self.Button_h[7].text():
                return
            else:
                self.change_comboBox(self.Button_h[7].text())
        except Exception as e:
            print("Function_Buttonclickh8:" + repr(e))

    def Function_Buttonclickh9(self):
        try:
            if '最近访问' in self.Button_h[8].text():
                return
            else:
                self.change_comboBox(self.Button_h[8].text())
        except Exception as e:
            print("Function_Buttonclickh9:" + repr(e))

    def Function_Buttonclickh10(self):
        try:
            if '最近访问' in self.Button_h[9].text():
                return
            else:
                self.change_comboBox(self.Button_h[9].text())
        except Exception as e:
            print("Function_Buttonclickh10:" + repr(e))

    def Function_Buttonclickh11(self):
        try:
            if '最近访问' in self.Button_h[10].text():
                return
            else:
                self.change_comboBox(self.Button_h[10].text())
        except Exception as e:
            print("Function_Buttonclickh11:" + repr(e))

    def Function_Buttonclickh12(self):
        try:
            if '最近访问' in self.Button_h[11].text():
                return
            else:
                self.change_comboBox(self.Button_h[11].text())
        except Exception as e:
            print("Function_Buttonclickh12:" + repr(e))

    def Function_Buttonclickt1(self):
        try:
            if '最近交易' in self.Button_t[0].text():
                return
            else:
                self.change_comboBox(self.Button_t[0].text())
        except Exception as e:
            print("Function_Buttonclickt1:" + repr(e))

    def Function_Buttonclickt2(self):
        try:
            if '最近交易' in self.Button_t[1].text():
                return
            else:
                self.change_comboBox(self.Button_t[1].text())
        except Exception as e:
            print("Function_Buttonclickt2:" + repr(e))

    def Function_Buttonclickt3(self):
        try:
            if '最近交易' in self.Button_t[2].text():
                return
            else:
                self.change_comboBox(self.Button_t[2].text())
        except Exception as e:
            print("Function_Buttonclickt3:" + repr(e))

    def Function_Buttonclickt4(self):
        try:
            if '最近交易' in self.Button_t[3].text():
                return
            else:
                self.change_comboBox(self.Button_t[3].text())
        except Exception as e:
            print("Function_Buttonclickt4:" + repr(e))

    def Function_Buttonclickt5(self):
        try:
            if '最近交易' in self.Button_t[4].text():
                return
            else:
                self.change_comboBox(self.Button_t[4].text())
        except Exception as e:
            print("Function_Buttonclickt5:" + repr(e))

    def Function_Buttonclickt6(self):
        try:
            if '最近交易' in self.Button_t[5].text():
                return
            else:
                self.change_comboBox(self.Button_t[5].text())
        except Exception as e:
            print("Function_Buttonclickt6:" + repr(e))

    def Function_Buttonclickt7(self):
        try:
            if '最近交易' in self.Button_t[6].text():
                return
            else:
                self.change_comboBox(self.Button_t[6].text())
        except Exception as e:
            print("Function_Buttonclickt7:" + repr(e))

    def Function_Buttonclickt8(self):
        try:
            if '最近交易' in self.Button_t[7].text():
                return
            else:
                self.change_comboBox(self.Button_t[7].text())
        except Exception as e:
            print("Function_Buttonclickt8:" + repr(e))

    def Function_Buttonclickt9(self):
        try:
            if '最近交易' in self.Button_t[8].text():
                return
            else:
                self.change_comboBox(self.Button_t[8].text())
        except Exception as e:
            print("Function_Buttonclickt9:" + repr(e))

    def Function_Buttonclickt10(self):
        try:
            if '最近交易' in self.Button_t[9].text():
                return
            else:
                self.change_comboBox(self.Button_t[9].text())
        except Exception as e:
            print("Function_Buttonclickt10:" + repr(e))

    def Function_Buttonclickt11(self):
        try:
            if '最近交易' in self.Button_t[10].text():
                return
            else:
                self.change_comboBox(self.Button_t[10].text())
        except Exception as e:
            print("Function_Buttonclickt11:" + repr(e))

    def Function_Buttonclickt12(self):
        try:
            if '最近交易' in self.Button_t[11].text():
                return
            else:
                self.change_comboBox(self.Button_t[11].text())
        except Exception as e:
            print("Function_Buttonclickt12:" + repr(e))

    def Function_Buttonclickz1(self):
        try:
            if '自选' in self.Button_zx[0].text():
                return
            else:
                self.change_comboBox(self.Button_zx[0].text())
        except Exception as e:
            print("Function_Buttonclickz1:" + repr(e))

    def Function_Buttonclickz2(self):
        try:
            if '自选' in self.Button_zx[1].text():
                return
            else:
                self.change_comboBox(self.Button_zx[1].text())
        except Exception as e:
            print("Function_Buttonclickz2:" + repr(e))

    def Function_Buttonclickz3(self):
        try:
            if '自选' in self.Button_zx[2].text():
                return
            else:
                self.change_comboBox(self.Button_zx[2].text())
        except Exception as e:
            print("Function_Buttonclickz3:" + repr(e))

    def Function_Buttonclickz4(self):
        try:
            if '自选' in self.Button_zx[3].text():
                return
            else:
                self.change_comboBox(self.Button_zx[3].text())
        except Exception as e:
            print("Function_Buttonclickz4:" + repr(e))

    def Function_Buttonclickz5(self):
        try:
            if '自选' in self.Button_zx[4].text():
                return
            else:
                self.change_comboBox(self.Button_zx[4].text())
        except Exception as e:
            print("Function_Buttonclickz5:" + repr(e))

    def Function_Buttonclickz6(self):
        try:
            if '自选' in self.Button_zx[5].text():
                return
            else:
                self.change_comboBox(self.Button_zx[5].text())
        except Exception as e:
            print("Function_Buttonclickz6:" + repr(e))

    def Function_Buttonclickz7(self):
        try:
            if '自选' in self.Button_zx[6].text():
                return
            else:
                self.change_comboBox(self.Button_zx[6].text())
        except Exception as e:
            print("Function_Buttonclickz7:" + repr(e))

    def Function_Buttonclickz8(self):
        try:
            if '自选' in self.Button_zx[7].text():
                return
            else:
                self.change_comboBox(self.Button_zx[7].text())
        except Exception as e:
            print("Function_Buttonclickz8:" + repr(e))

    def Function_Buttonclickz9(self):
        try:
            if '自选' in self.Button_zx[8].text():
                return
            else:
                self.change_comboBox(self.Button_zx[8].text())
        except Exception as e:
            print("Function_Buttonclickz9:" + repr(e))

    def Function_Buttonclickz10(self):
        try:
            if '自选' in self.Button_zx[9].text():
                return
            else:
                self.change_comboBox(self.Button_zx[9].text())
        except Exception as e:
            print("Function_Buttonclickz10:" + repr(e))

    def Function_Buttonclickz11(self):
        try:
            if '自选' in self.Button_zx[10].text():
                return
            else:
                self.change_comboBox(self.Button_zx[10].text())
        except Exception as e:
            print("Function_Buttonclickz11:" + repr(e))

    def Function_Buttonclickz12(self):
        try:
            if '自选' in self.Button_zx[11].text():
                return
            else:
                self.change_comboBox(self.Button_zx[11].text())
        except Exception as e:
            print("Function_Buttonclickz12:" + repr(e))

    def InitReadTalibcondition(self):
            with open("talib.csv", "r") as f:
                for line in f.readlines():
                    line = line.strip('\n')
                    strlist = line.split(",")
                    try:
                        if len(globalvar.dict_talibcondition[strlist[0]]) == 0:
                            pass
                    except Exception as e:
                        globalvar.dict_talibcondition[strlist[0]] = []
                        print("Function_Buttonclicke0 Error:" + repr(e))
                    globalvar.dict_talibcondition[strlist[0]].append(strlist)


    def Function_Buttonclicke0(self):
        if globalvar.DialogTalibState:
            return
        try:
            #print('len(globalvar.dict_talibcondition:'+str(len(globalvar.dict_talibcondition)))
            if len(globalvar.dict_talibcondition) == 0:
                self.InitReadTalibcondition()
        except Exception as e:
            self.InitReadTalibcondition()

        globalvar.DialogTalibState=True
        self.dlg_talibindicatrix = self.DialogTalib()
        self.dlg_talibindicatrix.setWindowTitle('Talib指标条件设置')
        self.dlg_talibindicatrix.show()
        screenRect = QApplication.desktop().screenGeometry()
        self.dlg_talibindicatrix.resize(0.58 * screenRect.width(), 0.60 * screenRect.height())
        # 居中窗口
        screen = QDesktopWidget().screenGeometry()
        size = self.dlg_talibindicatrix.geometry()
        self.dlg_talibindicatrix.move((screen.width() - size.width()) / 2,
                                 (screen.height() - size.height()) / 2)
        self.dlg_talibindicatrix.exec_()

    def Function_Buttonclicke1(self):
        dlg_myindicatrix = self.DialogTalib()
        dlg_myindicatrix.setWindowTitle('自定义指标')
        dlg_myindicatrix.show()
        screenRect = QApplication.desktop().screenGeometry()
        dlg_myindicatrix.resize(0.65 * screenRect.width(), 0.65 * screenRect.height())
        # 居中窗口
        screen = QDesktopWidget().screenGeometry()
        size = dlg_myindicatrix.geometry()
        dlg_myindicatrix.move((screen.width() - size.width()) / 2,
                              (screen.height() - size.height()) / 2)
        dlg_myindicatrix.exec_()

    def Function_Buttonclicke2(self):
        dlg_talibperiod = self.DialogTalib()
        # dlg_talibperiod.centralWidget()
        # 居中窗口
        screen = QDesktopWidget().screenGeometry()
        size = dlg_talibperiod.geometry()
        dlg_talibperiod.move((screen.width() - size.width()) / 2 - 75,
                             (screen.height() - size.height()) / 2 - 10)
        dlg_talibperiod.setWindowTitle('Talib指标')
        dlg_talibperiod.show()
        dlg_talibperiod.resize(600, 440)
        # self.childwidget = self.childwidget(self)
        dlg_talibperiod.exec_()

    def Function_Buttonclicke3(self):
        dlg_talibinstrumentid = self.DialogTalib()
        # dlg_talibinstrumentid.centralWidget()
        # 居中窗口
        screen = QDesktopWidget().screenGeometry()
        size = dlg_talibinstrumentid.geometry()
        dlg_talibinstrumentid.move((screen.width() - size.width()) / 2 - 75,
                                   (screen.height() - size.height()) / 2 - 10)
        dlg_talibinstrumentid.setWindowTitle('Talib指标')
        dlg_talibinstrumentid.show()
        dlg_talibinstrumentid.resize(600, 440)
        # self.childwidget = self.childwidget(self)
        dlg_talibinstrumentid.exec_()
        pass
        '''
        self.Button_e0.setEnabled(True)
        self.Button_e1.setEnabled(True)
        self.Button_e2.setEnabled(True)
        self.Button_e3.setEnabled(False)
        self.Button_e4.setEnabled(True)
        self.Button_e5.setEnabled(True)
        '''

    def Function_Buttonclicke4(self):
        pass

    def Function_Buttonclicke5(self):
        pass
        '''
        self.Button_e0.setEnabled(True)
        self.Button_e5.setEnabled(False)
        '''

    def SetBarMDState(self, state):
        if state == 1:
            self.lab_md.setPixmap(QPixmap('ico_error_mdconnect.png'))
        elif state == 2:
            self.lab_md.setPixmap(QPixmap('ico_right_mdlogin.png'))
        elif state == 3:
            self.lab_md.setPixmap(QPixmap('ico_right_mdlogin.png'))

    def SetBarTDState(self, state):
        if state == 1:
            self.lab_td.setPixmap(QPixmap('ico_error_tdconnect.png'))
        elif state == 2:
            self.lab_td.setPixmap(QPixmap('ico_right_tdlogin.png'))
        elif state == 3:
            self.lab_td.setPixmap(QPixmap('ico_right_tdlogin.png'))

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.centralwidget)
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
        self.tabWidget.setTabPosition(QtWidgets.QTabWidget.East)
        self.tabWidget.setTabsClosable(True)
        self.tabWidget.setObjectName("tabWidget")
        self.tab = QtWidgets.QWidget()
        self.tab.setObjectName("tab")
        self.gridLayout = QtWidgets.QGridLayout(self.tab)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")
        self.groupBox = QtWidgets.QGroupBox(self.tab)
        self.groupBox.setObjectName("groupBox")
        self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.groupBox)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.toolBox1 = QtWidgets.QToolBox(self.groupBox)

        # 组标题 toolBox1
        self.toolBox1.setObjectName("")

        self.toolBox2 = QtWidgets.QToolBox(self.groupBox)
        self.toolBox2.setObjectName("toolBox2")

        self.page_order = QtWidgets.QWidget()
        self.page_order.setGeometry(QtCore.QRect(0, 0, 98, 44))
        self.page_order.setObjectName("page_order")
        self.gridLayout_instrument = QtWidgets.QGridLayout(self.page_order)
        self.gridLayout_instrument.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_instrument.setObjectName("gridLayout_instrument")
        """
        #1，1 委托记录
        self.lineEdit = QtWidgets.QLineEdit(self.page_order)
        self.lineEdit.setObjectName("lineEdit")
        self.gridLayout_instrument.addWidget(self.lineEdit, 0, 0, 1, 1)
        """
        self.table_order = QtWidgets.QTableWidget(self.page_order)
        self.table_order.setObjectName("table_Order")
        self.table_order.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_order.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_order.setEditTriggers(self.table_order.NoEditTriggers)
        self.table_order.setSelectionBehavior(self.table_order.SelectRows)
        self.table_order.setColumnCount(9)
        self.table_order.setRowCount(0)
        self.table_order.setHorizontalHeaderLabels(
            ['报单编号', '合约', '买卖', '开平', '报单状态', '报单数', '已成交手数', '价格', '报单时间', '交易所'])  # 设置表头文字
        self.table_order.setSortingEnabled(True)  # 设置表头可以自动排序

        self.gridLayout_instrument.addWidget(self.table_order, 0, 0, 1, 1)
        self.toolBox1.addItem(self.page_order, "")
        self.page_instrument = QtWidgets.QWidget()
        self.page_instrument.setGeometry(QtCore.QRect(0, 0, 98, 44))
        self.page_instrument.setObjectName("page_instrument")
        self.gridLayout_instrument = QtWidgets.QGridLayout(self.page_instrument)
        self.gridLayout_instrument.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_instrument.setObjectName("gridLayout_instrument")

        self.table_instrumentcx = QtWidgets.QTableWidget(self.page_instrument)
        self.table_instrumentcx.setObjectName("table_Order")
        self.table_instrumentcx.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_instrumentcx.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_instrumentcx.setEditTriggers(self.table_instrumentcx.NoEditTriggers)
        self.table_instrumentcx.setSelectionBehavior(self.table_instrumentcx.SelectRows)
        self.table_instrumentcx.setColumnCount(8)
        self.table_instrumentcx.setRowCount(4)
        self.table_instrumentcx.setHorizontalHeaderLabels(
            ['品种代码', '合约', '合约名', '交易所', '合约乘数', '最小价格变动单位', '保证金', '手续费'])  # 设置表头文字
        self.table_instrumentcx.setSortingEnabled(True)  # 设置表头可以自动排序
        self.gridLayout_instrument.addWidget(self.table_instrumentcx, 0, 0, 1, 1)

        self.toolBox2.addItem(self.page_instrument, "")
        self.page_trade = QtWidgets.QWidget()
        self.page_trade.setGeometry(QtCore.QRect(0, 0, 697, 210))
        self.page_trade.setObjectName("page_trade")
        self.gridLayout_position = QtWidgets.QGridLayout(self.page_trade)
        self.gridLayout_position.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_position.setObjectName("gridLayout_position")

        self.table_trade = QtWidgets.QTableWidget(self.page_trade)
        self.table_trade.setObjectName("table_trade")
        self.table_trade.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_trade.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_trade.setEditTriggers(self.table_trade.NoEditTriggers)
        self.table_trade.setSelectionBehavior(self.table_trade.SelectRows)
        self.table_trade.doubleClicked.connect(self.Function_doubleClicked_Trade)
        self.table_trade.setColumnCount(11)
        self.table_trade.setRowCount(0)
        self.table_trade.setHorizontalHeaderLabels(
            ['策略名称', '成交编号', '报单编号', '合约', '买卖', '开平', '成交价格', '委托手数', '成交时间', '交易所', '备注'])  # 设置表头文字
        self.table_trade.setSortingEnabled(True)  # 设置表头可以自动排序
        self.gridLayout_position.addWidget(self.table_trade, 1, 1, 1, 1)

        self.page_position = QtWidgets.QWidget()
        self.page_position.setGeometry(QtCore.QRect(0, 0, 697, 210))
        self.page_position.setObjectName("page_position")
        self.gridLayout_position = QtWidgets.QGridLayout(self.page_position)
        self.gridLayout_position.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_position.setObjectName("gridLayout_position")
        self.table_position = QtWidgets.QTableWidget(self.page_trade)
        self.table_position.setObjectName("table_trade")
        self.table_position.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_position.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_position.setEditTriggers(self.table_position.NoEditTriggers)
        self.table_position.setSelectionBehavior(self.table_position.SelectRows)
        self.table_position.setColumnCount(8)
        self.table_position.setRowCount(0)
        self.table_position.setHorizontalHeaderLabels(
            ['合约', '买卖', '总持仓', '今仓', '可平量', '占用保证金', '持仓成本', '持仓盈亏'])  # 设置表头文字
        # 设置行高
        self.table_position.setRowHeight(0, 35)
        self.table_position.setSortingEnabled(True)  # 设置表头可以自动排序
        # self.table_position.sortItems(1,  Qt.DescendingOrder)  # 设置按照第二列自动降序排序
        self.table_position.horizontalHeader().setStretchLastSection(True)  ##设置最后一列拉伸至最大
        # self.table_position.setItemDelegateForColumn(0,  self )  # 设置第0列不可编辑
        self.table_position.doubleClicked.connect(self.Function_doubleClicked_algorithmtrading_limit)

        # TOdo 优化7 在单元格内放置控件
        """
        comBox=QtWidgets.QComboBox()
        comBox.addItems(['卖','买'])
        comBox.setStyleSheet('QComboBox{margin:3px}')
        self.table_position.setCellWidget(0,1,comBox)
        """
        '''

        Trade_CancelBtn = QtWidgets.QPushButton('双击人工平仓')
        Trade_CancelBtn.setFlat(True)
        Trade_CancelBtn.setStyleSheet('background-color:#ff0000;');
        # searchBtn.setDown(True)
        Trade_CancelBtn.setStyleSheet('QPushButton{margin:3px}')
        self.table_position.setCellWidget(0, 6, Trade_CancelBtn)
        '''
        self.gridLayout_position.addWidget(self.table_position, 1, 1, 1, 1)
        self.toolBox1.addItem(self.page_trade, "")
        self.toolBox2.addItem(self.page_position, "")
        self.verticalLayout_3.addWidget(self.toolBox1)
        self.verticalLayout_3.addWidget(self.toolBox2)
        self.gridLayout.addWidget(self.groupBox, 1, 0, 1, 1)
        self.tabWidget_2 = QtWidgets.QTabWidget(self.tab)
        self.tabWidget_2.setObjectName("tabWidget_2")

        self.tab_strategy = QtWidgets.QWidget()
        self.tab_strategy.setObjectName("tab_strategy")
        self.tab_account = QtWidgets.QWidget()
        self.tab_account.setObjectName("tab_account")
        self.tab_plus = QtWidgets.QWidget()
        self.tab_plus.setObjectName("tab_plus")
        self.tab_marketdata = QtWidgets.QWidget()
        self.tab_marketdata.setObjectName("tab_marketdata")
        self.tab_instrument = QtWidgets.QWidget()
        self.tab_instrument.setObjectName("tab_instrument")
        self.tab_algorithmtrading = QtWidgets.QWidget()
        self.tab_algorithmtrading.setObjectName("tab_algorithmtrading")
        self.tab_listtdlog = QtWidgets.QWidget()
        self.tab_listtdlog.setObjectName("tab_listtdlog")
        self.tab_listmdlog = QtWidgets.QWidget()
        self.tab_listmdlog.setObjectName("tab_listmdlog")
        self.tab_historytd = QtWidgets.QWidget()
        self.tab_historytd.setObjectName("tab_historytd")
        self.tab_historymd = QtWidgets.QWidget()
        self.tab_historymd.setObjectName("tab_historymd")
        self.tab_data = QtWidgets.QWidget()
        self.tab_data.setObjectName("tab_data")
        self.tab_report = QtWidgets.QWidget()
        self.tab_report.setObjectName("tab_report")
        self.tab_result = QtWidgets.QWidget()
        self.tab_result.setObjectName("tab_result")
        self.tab_faq = QtWidgets.QWidget()
        self.tab_faq.setObjectName("tab_faq")
        self.tabWidget_2.addTab(self.tab_strategy, "")
        self.tabWidget_2.addTab(self.tab_account, "")
        self.tabWidget_2.addTab(self.tab_plus, "")
        self.tabWidget_2.addTab(self.tab_marketdata, "")
        self.tabWidget_2.addTab(self.tab_instrument, "")
        self.tabWidget_2.addTab(self.tab_algorithmtrading, "")
        self.tabWidget_2.addTab(self.tab_listtdlog, "")
        self.tabWidget_2.addTab(self.tab_listmdlog, "")
        self.tabWidget_2.addTab(self.tab_historytd, "")
        self.tabWidget_2.addTab(self.tab_historymd, "")
        self.tabWidget_2.addTab(self.tab_data, "")
        self.tabWidget_2.addTab(self.tab_report, "")
        self.tabWidget_2.addTab(self.tab_result, "")
        self.tabWidget_2.addTab(self.tab_faq, "")

        self.gridLayout_strategy = QtWidgets.QGridLayout(self.tab_strategy)
        self.gridLayout_strategy.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_strategy.setObjectName("gridLayout_strategy")
        # self.checkableButton = QtWidgets.QPushButton(self.tab_strategy)
        # self.checkableButton.setCheckable(True)
        # self.checkableButton.setChecked(True)
        # self.checkableButton.setObjectName("checkableButton")
        # self.gridLayout_strategy.addWidget(self.checkableButton, 1, 0, 1, 1)

        self.gridLayout_account = QtWidgets.QGridLayout(self.tab_account)
        self.gridLayout_account.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_account.setObjectName("gridLayout_account")

        self.table_account = QtWidgets.QTableWidget(self.tab_account)
        self.table_account.setObjectName("table_account")
        self.table_account.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_account.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_account.setColumnCount(10)
        self.table_account.setRowCount(1)
        self.table_account.setEditTriggers(self.table_account.NoEditTriggers)
        self.table_account.setSelectionBehavior(self.table_account.SelectRows)
        self.table_account.setHorizontalHeaderLabels(
            ['期货公司BrokeID', '期货账户', '静态权益', '动态权益', '收益率', '可用资金', '仓位(风险度)', '手续费', '可取资金', '上次更新时间'])  # 设置表头文字
        self.table_account.setColumnWidth(0, 120)
        self.table_account.setColumnWidth(4, 80)
        self.table_account.setColumnWidth(6, 80)
        self.table_account.setColumnWidth(9, 140)

        try:
            global config
            config = configparser.ConfigParser()
            # -read读取ini文件
            config.read('vnctptd.ini', encoding='utf-8')
            brokeid = config.get('setting', 'brokeid')
            investor = config.get('setting', 'investor')
            password = config.get('setting', 'password')
            appid = config.get('setting', 'appid')
            userproductinfo = config.get('setting', 'userproductinfo')
            authcode = config.get('setting', 'authcode')
            address1 = config.get('setting', 'address1')
            address2 = config.get('setting', 'address2')
            address3 = config.get('setting', 'address3')
            item = QTableWidgetItem(brokeid)
            self.table_account.setItem(0, 0, item)
            item = QTableWidgetItem(investor)
            self.table_account.setItem(0, 1, item)
            item = QTableWidgetItem('登录更新')  # 静态权益
            self.table_account.setItem(0, 2, item)
            item = QTableWidgetItem('登录更新')
            self.table_account.setItem(0, 3, item)
            item = QTableWidgetItem('0.0%')  # 今日盈亏
            self.table_account.setItem(0, 4, item)
            item = QTableWidgetItem('登录更新')
            self.table_account.setItem(0, 5, item)  # 可用权益
            item = QTableWidgetItem('登录更新')  # 仓位
            self.table_account.setItem(0, 6, item)
            item = QTableWidgetItem('登录更新')  # 手续费
            self.table_account.setItem(0, 7, item)
            item = QTableWidgetItem('登录更新')  # 可取资金
            self.table_account.setItem(0, 8, item)
            item = QTableWidgetItem('登录更新')
            self.table_account.setItem(0, 9, item)
        except Exception as e:
            print("login Error:" + repr(e))

        self.Button_AddStrategy = QPushButton("重新扫描策略目录")
        self.Button_OpenStrategyPath = QPushButton("打开策略目录")
        self.Button_ConditionCombination = QPushButton("指标条件组合策略(升级中)")
        self.Button_TalibCondition = QPushButton("Talib指标条件设置(升级中)")


        self.Button_StrategyInstructions = QPushButton("策略模块使用说明")
        self.Button_StrategyFunction = QPushButton("")
        self.Button_AddInvestor = QPushButton("添加或修改账户")
        self.Button_ModifyInvestor = QPushButton("如何申请穿透监管授权码")
        self.Button_AddInstrument = QPushButton("添加合约编码")
        self.Button_SelectMainInstrument = QPushButton("选择主力合约")
        self.Button_SelectAll = QPushButton("全部选择")
        self.Button_SelectNone = QPushButton("全部不选")
        self.Button_Simnow = QPushButton("注册模拟账户（仅限工作日白天）")
        self.Button_Kaihu = QPushButton("开立实盘账户")
        self.Button_Plus = QPushButton("Plus会员说明")
        self.Button_Community = QPushButton("社区登录注册")
        self.Button_BandPlus = QPushButton("绑定期货账号获取Plus")
        self.Button_Buyplus = QPushButton("购买Plus")
        self.Button_OpenBackTestingPath = QPushButton("打开回测报告目录")
        self.Button_SetServiceUser = QPushButton("设置数据会员账户")
        self.Button_BuyService = QPushButton("购买数据服务会员")
        self.Button_ClearTdLog = QPushButton("清除历史交易日志文件")
        self.Button_ClearMdLog = QPushButton("清除历史行情日志文件")
        self.Button_ClearTodayTdLog = QPushButton("清空今日交易日志")
        self.Button_ClearTodayMdLog = QPushButton("清空今日行情日志")
        self.Button_OpenAlgorithmicTradingPath = QPushButton("打开算法交易目录")
        self.Button_FaqKaihu = QPushButton("如何降低交易成本")
        self.Button_FaqDevelopmentEnvironment = QPushButton("开发环境")
        self.Button_Faq3 = QPushButton("FAQ3")
        self.Button_Faq4 = QPushButton("FAQ4")
        self.Button_Faq5 = QPushButton("FAQ5")
        self.Button_Faq6 = QPushButton("FAQ6")
        self.Button_Faq7 = QPushButton("FAQ7")
        self.Button_Faq8 = QPushButton("FAQ8")
        self.Button_Faq9 = QPushButton("FAQ9")
        self.Button_Faq10 = QPushButton("FAQ10")
        self.Button_Faq11 = QPushButton("FAQ11")
        self.Button_Faq12 = QPushButton("FAQ12")
        self.Button_Faq13 = QPushButton("FAQ13")
        self.Button_Faq14 = QPushButton("FAQ14")

        # tab_instrument

        self.gridLayout_instrument = QtWidgets.QGridLayout(self.tab_instrument)
        self.gridLayout_instrument.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_instrument.setObjectName("gridLayout_tab_instrument")

        self.table_instrument = QtWidgets.QTableWidget(self.tab_instrument)
        self.table_instrument.setObjectName("table_instrument")
        self.table_instrument.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_instrument.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_instrument.setEditTriggers(self.table_instrument.NoEditTriggers)
        self.table_instrument.setSelectionBehavior(self.table_instrument.SelectRows)
        self.table_instrument.doubleClicked.connect(self.Function_doubleClicked_Trade)
        self.table_instrument.setColumnCount(7)
        self.table_instrument.setRowCount(0)
        self.table_instrument.setHorizontalHeaderLabels(
            ['ID', '合约', '合约编码', '交易所', '1跳价差', '保证金', '手续费'])  # 设置表头文字
        self.table_instrument.setSortingEnabled(True)  # 设置表头可以自动排序
        self.gridLayout_instrument.addWidget(self.table_instrument, 0, 0, 2, 2)
        self.gridLayout_instrument.addWidget(self.Button_AddInstrument, 1, 0, 1, 1)
        self.gridLayout_instrument.addWidget(self.Button_SelectMainInstrument, 1, 1, 1, 1)
        self.gridLayout_instrument.addWidget(self.Button_SelectAll, 2, 0, 1, 1)
        self.gridLayout_instrument.addWidget(self.Button_SelectNone, 2, 1, 1, 1)

        # list_marketdata
        self.gridLayout_marketdata = QtWidgets.QGridLayout(self.tab_marketdata)
        self.gridLayout_marketdata.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_marketdata.setObjectName("gridLayout_marketdata")
        self.list_marketdata = QtWidgets.QListWidget(self.tab_marketdata)
        self.list_marketdata.setObjectName("list_marketdata")
        _translate = QtCore.QCoreApplication.translate
        __sortingEnabled = self.list_marketdata.isSortingEnabled()
        self.list_marketdata.setSortingEnabled(False)
        self.list_marketdata.setSortingEnabled(__sortingEnabled)
        self.gridLayout_marketdata.addWidget(self.list_marketdata, 0, 0, 1, 1)

        # 今日交易日志
        self.gridLayout_listtdlog = QtWidgets.QGridLayout(self.tab_listtdlog)
        self.gridLayout_listtdlog.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_listtdlog.setObjectName("gridLayout_listtdlog")
        self.table_listtdlog = QtWidgets.QListWidget(self.tab_listtdlog)
        self.table_listtdlog.setObjectName("table_listtdlog")
        _translate = QtCore.QCoreApplication.translate
        __sortingEnabled = self.table_listtdlog.isSortingEnabled()
        self.table_listtdlog.setSortingEnabled(False)
        self.table_listtdlog.setSortingEnabled(__sortingEnabled)
        self.gridLayout_listtdlog.addWidget(self.table_listtdlog, 0, 0, 1, 1)
        self.gridLayout_listtdlog.addWidget(self.Button_ClearTodayTdLog, 1, 0, 1, 1)

        # 今日行情日志
        self.gridLayout_listmdlog = QtWidgets.QGridLayout(self.tab_listmdlog)
        self.gridLayout_listmdlog.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_listmdlog.setObjectName("gridLayout_listmdlog")
        self.table_listmdlog = QtWidgets.QListWidget(self.tab_listmdlog)
        self.table_listmdlog.setObjectName("table_listmdlog")
        _translate = QtCore.QCoreApplication.translate
        __sortingEnabled = self.table_listmdlog.isSortingEnabled()
        self.table_listmdlog.setSortingEnabled(False)
        self.table_listmdlog.setSortingEnabled(__sortingEnabled)
        self.gridLayout_listmdlog.addWidget(self.table_listmdlog, 0, 0, 1, 1)
        self.gridLayout_listmdlog.addWidget(self.Button_ClearTodayMdLog, 1, 0, 1, 1)

        # 增值服务
        self.gridLayout_plus = QtWidgets.QGridLayout(self.tab_plus)
        self.gridLayout_plus.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_plus.setObjectName("gridLayout_plus")
        self.table_plus = QtWidgets.QTableWidget(self.tab_plus)
        self.table_plus.setObjectName("table_plus")
        self.table_plus.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_plus.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_plus.setColumnCount(7)
        self.table_plus.setRowCount(0)
        self.table_plus.setEditTriggers(self.table_plus.NoEditTriggers)
        self.table_plus.setHorizontalHeaderLabels(
            ['期货版Plus会员', '积分', '推荐人数', '多日K线数据', '有限期', '回测功能', '有效期'])  # 设置表头文字
        self.table_plus.setColumnWidth(0, 150)
        self.table_plus.setColumnWidth(1, 120)
        self.table_plus.setColumnWidth(2, 120)
        self.table_plus.setColumnWidth(3, 150)
        self.table_plus.setColumnWidth(4, 150)
        self.table_plus.setRowHeight(0, 35)
        Trade_InstrumentBtn = QtWidgets.QPushButton('合约设置')
        Trade_InstrumentBtn.setFlat(True)
        Trade_InstrumentBtn.setStyleSheet('background-color:#ff0000;')
        Trade_InstrumentBtn.setStyleSheet('QPushButton{margin:3px}')
        self.table_plus.setCellWidget(0, 6, Trade_InstrumentBtn)
        Trade_BacktestingBtn = QtWidgets.QPushButton('回测')
        Trade_BacktestingBtn.setFlat(True)
        Trade_BacktestingBtn.setStyleSheet('background-color:#ff0000;')
        Trade_BacktestingBtn.setStyleSheet('QPushButton{margin:3px}')
        self.table_plus.setCellWidget(0, 7, Trade_BacktestingBtn)
        Trade_BacktestingBtn = QtWidgets.QPushButton('查看策略仓位')
        Trade_BacktestingBtn.setFlat(True)
        Trade_BacktestingBtn.setStyleSheet('background-color:#ff0000;')
        Trade_BacktestingBtn.setStyleSheet('QPushButton{margin:3px}')
        self.gridLayout_plus.addWidget(self.table_plus, 0, 0, 2, 2)
        self.gridLayout_plus.addWidget(self.Button_Plus, 1, 0, 1, 1)
        self.gridLayout_plus.addWidget(self.Button_Community, 1, 1, 1, 1)
        self.gridLayout_plus.addWidget(self.Button_BandPlus, 2, 0, 1, 1)
        self.gridLayout_plus.addWidget(self.Button_Buyplus, 2, 1, 1, 1)

        # 策略
        self.table_strategy = QtWidgets.QTableWidget(self.tab_strategy)
        self.table_strategy.setObjectName("table_strategy")
        self.table_strategy.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_strategy.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_strategy.setColumnCount(9)
        self.table_strategy.setRowCount(0)
        self.table_strategy.setEditTriggers(self.table_strategy.NoEditTriggers)
        self.table_strategy.setHorizontalHeaderLabels(
            ['ID(勾选执行)', '策略名称', '策略文件名称(双击编辑，仅限英文名)', '胜率', '盈亏比', '今日交易', '合约设置', '回测', '查看策略仓位'])  # 设置表头文字
        self.table_strategy.doubleClicked.connect(self.Function_doubleClicked_strategy)
        self.table_strategy.setColumnWidth(2, 220)
        self.table_strategy.setRowHeight(0, 35)
        Trade_InstrumentBtn = QtWidgets.QPushButton('合约设置')
        Trade_InstrumentBtn.setFlat(True)
        Trade_InstrumentBtn.setStyleSheet('background-color:#ff0000;')
        # searchBtn.setDown(True)
        Trade_InstrumentBtn.setStyleSheet('QPushButton{margin:3px}')
        self.table_strategy.setCellWidget(0, 6, Trade_InstrumentBtn)
        Trade_BacktestingBtn = QtWidgets.QPushButton('回测')
        Trade_BacktestingBtn.setFlat(True)
        Trade_BacktestingBtn.setStyleSheet('background-color:#ff0000;')
        # searchBtn.setDown(True)
        Trade_BacktestingBtn.setStyleSheet('QPushButton{margin:3px}')
        self.table_strategy.setCellWidget(0, 7, Trade_BacktestingBtn)
        Trade_BacktestingBtn = QtWidgets.QPushButton('查看策略仓位')
        Trade_BacktestingBtn.setFlat(True)
        Trade_BacktestingBtn.setStyleSheet('background-color:#ff0000;')
        # searchBtn.setDown(True)
        Trade_BacktestingBtn.setStyleSheet('QPushButton{margin:3px}')
        self.table_strategy.setCellWidget(0, 8, Trade_BacktestingBtn)
        self.gridLayout_strategy.addWidget(self.table_strategy, 0, 0, 2, 2)

        self.gridLayout_strategy.addWidget(self.Button_AddStrategy, 1, 0, 1, 1)
        self.gridLayout_strategy.addWidget(self.Button_OpenStrategyPath, 1, 1, 1, 1)
        self.gridLayout_strategy.addWidget(self.Button_ConditionCombination, 2, 0, 1, 1)
        self.gridLayout_strategy.addWidget(self.Button_TalibCondition, 2, 1, 1, 1)
        self.gridLayout_account.addWidget(self.table_account, 0, 0, 2, 2)
        self.gridLayout_account.addWidget(self.Button_AddInvestor, 1, 0, 1, 1)
        self.gridLayout_account.addWidget(self.Button_ModifyInvestor, 1, 1, 1, 1)
        self.gridLayout_account.addWidget(self.Button_Kaihu, 2, 0, 1, 1)
        self.gridLayout_account.addWidget(self.Button_Simnow, 2, 1, 1, 1)

        # 常见问题
        self.gridLayout_faq = QtWidgets.QGridLayout(self.tab_faq)
        self.gridLayout_faq.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_faq.setObjectName("gridLayout_faq")
        self.gridLayout_faq.addWidget(self.Button_FaqKaihu, 0, 0, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_FaqDevelopmentEnvironment, 0, 1, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq3, 1, 0, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq4, 1, 1, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq5, 2, 0, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq6, 2, 1, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq7, 3, 0, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq8, 3, 1, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq9, 4, 0, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq10, 4, 1, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq11, 5, 0, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq12, 5, 1, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq13, 6, 0, 1, 1)
        self.gridLayout_faq.addWidget(self.Button_Faq14, 6, 1, 1, 1)

        # 算法交易
        self.gridLayout_algorithmtrading = QtWidgets.QGridLayout(self.tab_algorithmtrading)
        self.gridLayout_algorithmtrading.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_algorithmtrading.setObjectName("gridLayout_algorithmtrading")
        self.gridLayout.addWidget(self.tabWidget_2, 0, 0, 1, 1)
        self.gridLayout_historytd = QtWidgets.QGridLayout(self.tab_historytd)
        self.gridLayout_historytd.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_historytd.setObjectName("gridLayout_historytd")
        self.gridLayout_historymd = QtWidgets.QGridLayout(self.tab_historymd)
        self.gridLayout_historymd.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_historymd.setObjectName("gridLayout_historymd")
        self.gridLayout_data = QtWidgets.QGridLayout(self.tab_data)
        self.gridLayout_data.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_data.setObjectName("gridLayout_data")
        self.gridLayout_report = QtWidgets.QGridLayout(self.tab_report)
        self.gridLayout_report.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_report.setObjectName("gridLayout_report")
        self.table_data = QtWidgets.QTableWidget(self.tab_data)
        self.table_data.setObjectName("table_data")
        self.table_data.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_data.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_data.setColumnCount(8)
        self.table_data.setRowCount(4)
        self.gridLayout_data.addWidget(self.table_data, 0, 0, 2, 2)
        self.gridLayout_data.addWidget(self.Button_SetServiceUser, 1, 0, 1, 1)
        self.gridLayout_data.addWidget(self.Button_BuyService, 1, 1, 1, 1)

        # --------------------------------------
        # 历史交易日志标签
        self.table_historytd = QtWidgets.QTableWidget(self.tab_historytd)
        self.table_historytd.setObjectName("table_historytd")
        self.table_historytd.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_historytd.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_historytd.setColumnCount(7)
        self.table_historytd.setRowCount(0)
        self.table_historytd.setRowHeight(0, 28)
        self.table_historytd.setEditTriggers(self.table_historytd.NoEditTriggers)
        self.table_historytd.setHorizontalHeaderLabels(
            ['ID', '日期', '时间', '期货公司', '账户', '错误', '操作'])  # 设置表头文字
        self.table_historytd.doubleClicked.connect(self.Function_doubleClicked_historytd)
        self.Trade_historytdBtn = QPushButton("打开日志")
        self.table_historytd.setCellWidget(0, 6, self.Trade_historytdBtn)
        self.Trade_historytdBtn.clicked.connect(self.Function_OpenLog_TD)

        self.gridLayout_historytd.addWidget(self.table_historytd, 0, 0, 1, 1)
        self.gridLayout_historytd.addWidget(self.Button_ClearTdLog, 1, 0, 1, 1)
        self.Button_ClearTdLog.clicked.connect(self.Function_ClearTdLog)

        self.gridLayout_result = QtWidgets.QGridLayout(self.tab_result)
        self.gridLayout_result.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_result.setObjectName("gridLayout_result")

        self.table_result = QtWidgets.QTableWidget(self.tab_result)
        self.table_result.setObjectName("table_result")
        self.table_result.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_result.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_result.setColumnCount(9)
        self.table_result.setRowCount(0)
        self.table_result.setEditTriggers(self.table_result.NoEditTriggers)
        self.table_result.setHorizontalHeaderLabels(
            ['ID', '策略', '执行合约数', '胜率', '盈亏比', '今日交易', '合约设置', '回测', '查看策略仓位'])  # 设置表头文字
        # 设置行高
        self.table_result.setRowHeight(0, 35)
        self.gridLayout_result.addWidget(self.table_result, 0, 0, 2, 2)

        self.table_report = QtWidgets.QTableWidget(self.tab_report)
        self.table_report.setObjectName("table_result")
        self.table_report.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_report.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_report.setColumnCount(13)
        self.table_report.setRowCount(0)
        self.table_report.setEditTriggers(self.table_report.NoEditTriggers)
        self.table_report.setHorizontalHeaderLabels(
            ['ID', '策略', '回测周期', '合约', '完成进度', '参数1', '步长1', '参数2', '步长2', '参数3', '步长3', '参数4', '步长4'])  # 设置表头文字
        self.table_report.setColumnWidth(0, 90)
        self.table_report.setColumnWidth(1, 110)
        self.table_report.setColumnWidth(4, 110)
        self.table_report.setColumnWidth(5, 70)
        self.table_report.setColumnWidth(6, 70)
        self.table_report.setColumnWidth(7, 70)
        self.table_report.setColumnWidth(8, 70)
        self.table_report.setColumnWidth(9, 70)
        self.table_report.setColumnWidth(10, 70)
        self.table_report.setColumnWidth(11, 70)
        self.table_report.setColumnWidth(12, 70)
        # 设置行高
        self.table_report.setRowHeight(0, 35)
        self.gridLayout_report.addWidget(self.table_report, 0, 0, 2, 2)
        '''
        Trade_historytdBtn = QtWidgets.QPushButton('打开日志')
        Trade_historytdBtn.setFlat(True)
        Trade_historytdBtn.setStyleSheet('background-color:#ff0000;');
        # searchBtn.setDown(True)
        Trade_historytdBtn.setStyleSheet('QPushButton{margin:3px}')
        '''

        # 历史行情日志标签
        self.table_historymd = QtWidgets.QTableWidget(self.tab_historymd)
        self.table_historymd.setObjectName("table_historymd")
        self.table_historymd.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_historymd.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_historymd.setColumnCount(7)
        self.table_historymd.setRowCount(0)
        self.table_historymd.setRowHeight(0, 28)
        self.table_historymd.setEditTriggers(self.table_historymd.NoEditTriggers)
        self.table_historymd.setHorizontalHeaderLabels(
            ['ID', '日期', '时间', '期货公司', '账户', '错误', '操作'])  # 设置表头文字
        self.table_historymd.doubleClicked.connect(self.Function_doubleClicked_historymd)
        self.Trade_historymdBtn = QPushButton("打开日志")
        self.table_historymd.setCellWidget(0, 6, self.Trade_historymdBtn)
        self.Trade_historymdBtn.clicked.connect(self.Function_OpenLog_MD)

        self.gridLayout_historymd.addWidget(self.table_historymd, 0, 0, 1, 1)
        self.gridLayout_historymd.addWidget(self.Button_ClearMdLog, 1, 0, 1, 1)
        self.Button_ClearMdLog.clicked.connect(self.Function_ClearMdLog)

        # 算法交易
        self.table_algorithmtrading = QtWidgets.QTableWidget(self.tab_algorithmtrading)
        self.table_algorithmtrading.setObjectName("table_algorithmtrading")
        self.table_algorithmtrading.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_algorithmtrading.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_algorithmtrading.setColumnCount(7)
        self.table_algorithmtrading.setRowCount(1)
        self.table_algorithmtrading.setRowHeight(0, 28)
        self.table_algorithmtrading.setEditTriggers(self.table_algorithmtrading.NoEditTriggers)
        self.table_algorithmtrading.setSelectionBehavior(self.table_algorithmtrading.SelectRows)
        self.table_algorithmtrading.setHorizontalHeaderLabels(
            ['交易算法', '算法交易路径', '节省滑点', '参数1', '参数2', '参数3', '参数4'])  # 设置表头文字
        self.gridLayout_algorithmtrading.addWidget(self.table_algorithmtrading, 0, 0, 1, 1)
        self.gridLayout_algorithmtrading.addWidget(self.Button_OpenAlgorithmicTradingPath, 1, 0, 1, 1)
        self.Button_OpenAlgorithmicTradingPath.clicked.connect(self.Function_OpenAlgorithmicTradingPath)
        self.table_algorithmtrading.doubleClicked.connect(self.Function_doubleClicked_algorithmtrading_limit)

        def function_item_clicked(self, QTableWidgetItem):
            check_state = QTableWidgetItem.checkState()
            row = QTableWidgetItem.row()
            if check_state == QtCore.Qt.Checked:
                if row not in self.delete_row:
                    self.delete_row.append(row)
            elif check_state == QtCore.Qt.Unchecked:
                if row in self.delete_row:
                    self.delete_row.remove(row)

        item = QTableWidgetItem(' 限价单')
        item.setCheckState(QtCore.Qt.Checked)

        # item.connect(self.table_algorithmtrading, QtCore.SIGNAL("itemClicked(QTableWidgetItem*)"), self.function_item_clicked)

        self.table_algorithmtrading.setItem(0, 0, item)
        item = QTableWidgetItem('')
        self.table_algorithmtrading.setItem(0, 1, item)
        item = QTableWidgetItem('')
        self.table_algorithmtrading.setItem(0, 2, item)
        '''
        item = QTableWidgetItem(' TWAP')
        item.setCheckState(QtCore.Qt.Unchecked)
        self.table_algorithmtrading.setItem(1, 0, item)
        item = QTableWidgetItem('')
        self.table_algorithmtrading.setItem(1, 1, item)
        item = QTableWidgetItem('')
        self.table_algorithmtrading.setItem(1, 2, item)
        '''

        # Algorithmic Trading

        # self.Trade_historymdBtn.clicked.connect(self.Function_OpenLog_MD)

        # -------------------------------------

        self.table_data.setEditTriggers(self.table_data.NoEditTriggers)
        self.table_data.setColumnCount(8)
        self.table_data.setRowCount(4)
        self.table_data.setHorizontalHeaderLabels(['ID', '开始日期', '结束日期', '数据大小', '周期', '进度', '数据', '数据服务会员'])  # 设置表头文字
        # 设置行高

        self.table_data.setRowHeight(0, 35)
        self.table_data.setColumnWidth(5, 250)
        self.table_data.setColumnWidth(7, 300)
        Trade_DownloadData = QtWidgets.QPushButton('下载数据')
        Trade_DownloadData.setFlat(True)
        Trade_DownloadData.setStyleSheet('background-color:#ff0000;')
        # searchBtn.setDown(True)
        Trade_DownloadData.setStyleSheet('QPushButton{margin:3px}')
        self.table_data.setCellWidget(0, 6, Trade_DownloadData)
        # Trade_DownloadData.triggered.connect(self.Function_OpenUrl_COOLQUANT)
        Trade_DownloadData.clicked.connect(self.OnStart)

        """

        self.dateEdit = QtWidgets.QDateEdit(self.tab)
        self.dateEdit.setObjectName("dateEdit")
        self.gridLayout.addWidget(self.dateEdit, 2, 0, 1, 1)
        """
        self.tabWidget.addTab(self.tab, "")
        self.tab_2 = QtWidgets.QWidget()
        self.tab_2.setObjectName("tab_2")
        self.gridLayout_2 = QtWidgets.QGridLayout(self.tab_2)
        self.gridLayout_2.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.groupBox_2 = QtWidgets.QGroupBox(self.tab_2)
        self.groupBox_2.setObjectName("groupBox_2")
        self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.groupBox_2)
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.label = QtWidgets.QLabel(self.groupBox_2)
        self.label.setObjectName("label")
        self.verticalLayout_4.addWidget(self.label)
        self.radioButton = QtWidgets.QRadioButton(self.groupBox_2)
        self.radioButton.setObjectName("radioButton")
        self.verticalLayout_4.addWidget(self.radioButton)
        self.checkBox = QtWidgets.QCheckBox(self.groupBox_2)
        self.checkBox.setObjectName("checkBox")
        self.verticalLayout_4.addWidget(self.checkBox)
        self.checkBox_2 = QtWidgets.QCheckBox(self.groupBox_2)
        self.checkBox_2.setTristate(True)
        self.checkBox_2.setObjectName("checkBox_2")
        self.verticalLayout_4.addWidget(self.checkBox_2)
        self.treeWidget = QtWidgets.QTreeWidget(self.groupBox_2)
        self.treeWidget.setObjectName("treeWidget")
        item_0 = QtWidgets.QTreeWidgetItem(self.treeWidget)
        item_0 = QtWidgets.QTreeWidgetItem(self.treeWidget)
        self.verticalLayout_4.addWidget(self.treeWidget)
        self.gridLayout_2.addWidget(self.groupBox_2, 0, 0, 1, 1)
        self.tabWidget.addTab(self.tab_2, "")
        self.verticalLayout_5.addWidget(self.tabWidget)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")

        self.menu_b_popup = QtWidgets.QToolButton(self.centralwidget)
        self.menu_b_popup.setPopupMode(QtWidgets.QToolButton.InstantPopup)
        self.menu_b_popup.setObjectName("menu_b_popup")
        self.horizontalLayout.addWidget(self.menu_b_popup)

        self.Button_Start = QtWidgets.QPushButton(self.centralwidget)
        self.Button_Start.setObjectName("Button_Start")
        self.horizontalLayout.addWidget(self.Button_Start)
        # self.menu_a_popup = QtWidgets.QToolButton(self.centralwidget)
        # self.menu_a_popup.setObjectName("menu_a_popup")
        # self.horizontalLayout.addWidget(self.menu_a_popup)

        # self.menu_c_popup = QtWidgets.QToolButton(self.centralwidget)
        # self.menu_c_popup.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup)
        # self.menu_c_popup.setObjectName("menu_c_popup")
        # self.horizontalLayout.addWidget(self.menu_c_popup)
        # self.line_2 = QtWidgets.QFrame(self.centralwidget)
        # self.line_2.setFrameShape(QtWidgets.QFrame.VLine)
        # self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
        # self.line_2.setObjectName("line_2")
        # self.horizontalLayout.addWidget(self.line_2)
        self.Button_Stop = QtWidgets.QPushButton(self.centralwidget)
        self.Button_Stop.setEnabled(False)
        self.Button_Stop.setObjectName("Button_Stop")
        self.horizontalLayout.addWidget(self.Button_Stop)

        self.lab_md = QLabel()
        self.lab_md.setPixmap(QPixmap('ico_error_mdconnect.png'))
        self.horizontalLayout.addWidget(self.lab_md)

        self.lab_td = QLabel()
        self.lab_td.setPixmap(QPixmap('ico_error_tdconnect.png'))
        self.horizontalLayout.addWidget(self.lab_td)

        '''
        self.label_1 = QLabel()
        self.label_1.setPixmap(QPixmap('error.png'))
        self.label_1.setText("行情已连接，未登录")
        self.label_1.setAutoFillBackground(True)
        self.palette = QPalette()
        self.palette.setColor(QPalette.Window, Qt.blue)
        self.label_1.setPalette(self.palette)
        self.label_1.setAlignment(Qt.AlignCenter)
        self.horizontalLayout.addWidget(self.label_1)
        '''

        # self.doubleSpinBox = QtWidgets.QDoubleSpinBox(self.centralwidget)
        # self.doubleSpinBox.setObjectName("doubleSpinBox")
        # self.horizontalLayout.addWidget(self.doubleSpinBox)
        self.toolButton = QtWidgets.QToolButton(self.centralwidget)
        self.toolButton.setPopupMode(QtWidgets.QToolButton.InstantPopup)
        self.toolButton.setObjectName("toolButton")
        self.horizontalLayout.addWidget(self.toolButton)
        self.verticalLayout_5.addLayout(self.horizontalLayout)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1068, 23))
        self.menubar.setObjectName("menubar")
        self.menuMenu_nav1 = QtWidgets.QMenu(self.menubar)
        self.menuMenu_nav1.setObjectName("menuMenu")

        self.menuMenu_nav2 = QtWidgets.QMenu(self.menubar)
        self.menuMenu_nav2.setObjectName("menuMenub")

        self.menuMenu_nav3 = QtWidgets.QMenu(self.menubar)
        self.menuMenu_nav3.setObjectName("menuMenub")

        self.menuSubmenu_2 = QtWidgets.QMenu(self.menuMenu_nav1)
        self.menuSubmenu_2.setObjectName("menuSubmenu_2")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.dockWidget1 = QtWidgets.QDockWidget(MainWindow)
        self.dockWidget1.setObjectName("dockWidget1")
        # self.dockWidget1.setFixedSize(800, QDesktopWidget().availableGeometry().height() - 20)  # 分别为宽度和高度

        MainWindow.setFixedSize(QDesktopWidget().availableGeometry().width(),
                                QDesktopWidget().availableGeometry().height())

        self.dockWidgetContents = QtWidgets.QWidget()
        self.dockWidgetContents.setObjectName("dockWidgetContents")

        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.dockWidgetContents)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.comboBox_kline = QtWidgets.QComboBox()
        # self.comboBox_kline.setFixedWidth(180)
        self.comboBox_kline.setObjectName("comboBox_kline")
        self.comboBox_kline.setFixedWidth(180)
        self.comboBox_kline.addItem("")
        self.comboBox_kline.addItem("")
        self.comboBox_kline.addItem("")
        self.comboBox_kline.addItem("")
        self.comboBox_kline.addItem("")
        self.comboBox_kline.addItem("")
        self.comboBox_kline.addItem("")
        self.comboBox_kline.addItem("")
        self.verticalLayout.addWidget(self.comboBox_kline)
        self.verticalLayout.addStretch(1)  # 与上面1：1 空白拉伸

        self.comboBox_exchange = QtWidgets.QComboBox()
        self.comboBox_exchange.setFixedWidth(180)
        self.comboBox_exchange.setObjectName("comboBox_exchange")
        self.comboBox_exchange.addItem("")
        self.comboBox_exchange.addItem("")
        self.comboBox_exchange.addItem("")
        self.comboBox_exchange.addItem("")
        self.comboBox_exchange.addItem("")
        self.comboBox_exchange.addItem("")
        self.comboBox_exchange.addItem("")
        self.comboBox_exchange.addItem("")
        self.verticalLayout.addWidget(self.comboBox_exchange)
        self.verticalLayout.addStretch(1)  # 与上面1：1 空白拉伸

        self.comboBox_instrument = QtWidgets.QComboBox()
        self.comboBox_instrument.setFixedWidth(180)
        self.comboBox_instrument.setObjectName("comboBox_instrument")
        self.comboBox_instrument.addItem("选择合约类型编码")
        self.verticalLayout.addWidget(self.comboBox_instrument)
        self.verticalLayout.addStretch(1)  # 与上面1：1 空白拉伸

        self.comboBox_instrumentid = QtWidgets.QComboBox()
        self.comboBox_instrumentid.setFixedWidth(180)
        self.comboBox_instrumentid.setObjectName("comboBox_instrumentid")

        self.comboBox_kline.activated.connect(lambda: self.to_comboBox_klineperiod(self.comboBox_kline.currentText()))
        self.comboBox_exchange.activated.connect(lambda: self.to_comboBox_1(self.comboBox_exchange.currentText()))
        self.comboBox_instrument.activated.connect(lambda: self.to_comboBox_2(self.comboBox_instrument.currentText()))
        self.comboBox_instrumentid.activated.connect(
            lambda: self.to_comboBox_3(self.comboBox_instrumentid.currentText()))

        self.verticalLayout_2.addLayout(self.verticalLayout)
        self.frame_comboBox = QtWidgets.QFrame(self.comboBox_kline)
        self.frame_comboBox.setMinimumSize(QtCore.QSize(0, 0))
        self.frame_comboBox.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame_comboBox.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame_comboBox.setLineWidth(3)
        self.frame_comboBox.setObjectName("frame_comboBox")
        self.verticalLayout.addWidget(self.frame_comboBox)

        self.gridLayout_comboBox = QtWidgets.QGridLayout(self.frame_comboBox)
        self.gridLayout_comboBox.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_comboBox.setObjectName("gridLayout_optionalstock222")

        self.gridLayout_comboBox.addWidget(self.comboBox_kline, 4, 0, 1, 1)
        self.gridLayout_comboBox.addWidget(self.comboBox_exchange, 4, 1, 1, 1)
        self.gridLayout_comboBox.addWidget(self.comboBox_instrument, 4, 2, 1, 1)
        self.gridLayout_comboBox.addWidget(self.comboBox_instrumentid, 4, 3, 1, 1)

        # K线图位置
        # global logYdata
        self.item = CandlestickItem(data_kline)  # 原始数据,对应（0,0）幅图
        npdata = np.array(data_kline)
        # logYdata = np.log(npdata[:, 1:])
        # self.logYdata = np.log(npdata[1:, 2:])
        # self.logYdata = np.insert(self.logYdata, 0, values=npdata[:, 0], axis=1)
        # self.logYdata = list(map(tuple, self.logYdata))
        self.wkline = pg.GraphicsWindow()
        self.wkline.setWindowTitle('pyqtgraph example: customGraphicsItem')

        self.plt_kline = self.wkline.addPlot(1, 1, title="K线图")

        self.plt_kline.addItem(self.item)
        self.plt_kline.showGrid(True, True)
        self.plt_kline.setMouseEnabled(x=True, y=True)  # 禁用轴操作
        self.verticalLayout.addWidget(self.wkline)
        self.wkline.showMaximized()
        # K线图位置

        # 分时图
        self.winmarket = pg.GraphicsLayoutWidget(show=True)
        self.winmarket.setWindowTitle('闪电图')
        self.plt_market = self.winmarket.addPlot(title="闪电图")
        # plt_market.setAutoVisibleOnly(y=True)
        self.curve_market = self.plt_market.plot()
        self.plt_market.setMouseEnabled(x=False, y=False)  # 禁用轴操作
        self.verticalLayout.addWidget(self.winmarket)
        self.winmarket.showMaximized()
        # 分时图

        # Tab1 实时资金曲线位置
        self.win = pg.GraphicsLayoutWidget(show=True)
        self.win.setWindowTitle('实时资金曲线(10秒取样1次)')
        self.plt_realtime = self.win.addPlot(title="实时资金曲线(10秒取样1次)")
        # self.win.setBackground('y')
        # plt_realtime.setAutoVisibleOnly(y=True)
        self.curve_realtime = self.plt_realtime.plot(pen='y')
        self.plt_realtime.setMouseEnabled(x=False, y=False)  # 禁用轴操作
        self.verticalLayout.addWidget(self.win)
        self.win.showMaximized()
        # Tab1 实时资金曲线位置

        # 进度条
        self.progressBar = QtWidgets.QProgressBar(self.dockWidgetContents)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setFormat("仓位：%p%")
        self.progressBar.setObjectName("总仓位")
        self.verticalLayout.addWidget(self.progressBar)
        # 决定绘图多窗口
        self.verticalLayout_2.addLayout(self.verticalLayout)

        self.Button_h = []

        self.temps = QtWidgets.QPushButton('最近访问1')
        self.temps.setObjectName("Button_h1")
        self.temps.clicked.connect(self.Function_Buttonclickh1)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问2')
        self.temps.setObjectName("Button_h2")
        self.temps.clicked.connect(self.Function_Buttonclickh2)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问3')
        self.temps.setObjectName("Button_h3")
        self.temps.clicked.connect(self.Function_Buttonclickh3)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问4')
        self.temps.setObjectName("Button_h4")
        self.temps.clicked.connect(self.Function_Buttonclickh4)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问5')
        self.temps.setObjectName("Button_h5")
        self.temps.clicked.connect(self.Function_Buttonclickh5)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问6')
        self.temps.setObjectName("Button_h6")
        self.temps.clicked.connect(self.Function_Buttonclickh6)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问7')
        self.temps.setObjectName("Button_h7")
        self.temps.clicked.connect(self.Function_Buttonclickh7)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问8')
        self.temps.setObjectName("Button_h8")
        self.temps.clicked.connect(self.Function_Buttonclickh8)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问9')
        self.temps.setObjectName("Button_h9")
        self.temps.clicked.connect(self.Function_Buttonclickh9)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问10')
        self.temps.setObjectName("Button_h10")
        self.temps.clicked.connect(self.Function_Buttonclickh10)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问11')
        self.temps.setObjectName("Button_h11")
        self.temps.clicked.connect(self.Function_Buttonclickh11)
        self.Button_h.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近访问12')
        self.temps.setObjectName("Button_h12")
        self.temps.clicked.connect(self.Function_Buttonclickh12)
        self.Button_h.append(self.temps)

        self.Button_t = []

        self.temps = QtWidgets.QPushButton('最近交易1')
        self.temps.setObjectName("Button_t1")
        self.temps.clicked.connect(self.Function_Buttonclickt1)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易2')
        self.temps.setObjectName("Button_t2")
        self.temps.clicked.connect(self.Function_Buttonclickt2)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易3')
        self.temps.setObjectName("Button_t3")
        self.temps.clicked.connect(self.Function_Buttonclickt3)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易4')
        self.temps.setObjectName("Button_t4")
        self.temps.clicked.connect(self.Function_Buttonclickt4)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易5')
        self.temps.setObjectName("Button_t5")
        self.temps.clicked.connect(self.Function_Buttonclickt5)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易6')
        self.temps.setObjectName("Button_t6")
        self.temps.clicked.connect(self.Function_Buttonclickt6)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易7')
        self.temps.setObjectName("Button_t7")
        self.temps.clicked.connect(self.Function_Buttonclickt7)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易8')
        self.temps.setObjectName("Button_t8")
        self.temps.clicked.connect(self.Function_Buttonclickt8)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易9')
        self.temps.setObjectName("Button_t9")
        self.temps.clicked.connect(self.Function_Buttonclickt9)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易10')
        self.temps.setObjectName("Button_t10")
        self.temps.clicked.connect(self.Function_Buttonclickt10)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易11')
        self.temps.setObjectName("Button_t11")
        self.temps.clicked.connect(self.Function_Buttonclickt11)
        self.Button_t.append(self.temps)

        self.temps = QtWidgets.QPushButton('最近交易12')
        self.temps.setObjectName("Button_t12")
        self.temps.clicked.connect(self.Function_Buttonclickt12)
        self.Button_t.append(self.temps)

        self.Button_zx = []

        self.temps = QtWidgets.QPushButton('自选1')
        self.temps.setObjectName("Button_zx1")
        self.temps.clicked.connect(self.Function_Buttonclickz1)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选2')
        self.temps.setObjectName("Button_zx2")
        self.temps.clicked.connect(self.Function_Buttonclickz2)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选3')
        self.temps.setObjectName("Button_zx3")
        self.temps.clicked.connect(self.Function_Buttonclickz3)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选4')
        self.temps.setObjectName("Button_zx4")
        self.temps.clicked.connect(self.Function_Buttonclickz4)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选5')
        self.temps.setObjectName("Button_zx5")
        self.temps.clicked.connect(self.Function_Buttonclickz5)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选6')
        self.temps.setObjectName("Button_zx6")
        self.temps.clicked.connect(self.Function_Buttonclickz6)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选7')
        self.temps.setObjectName("Button_zx7")
        self.temps.clicked.connect(self.Function_Buttonclickz7)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选8')
        self.temps.setObjectName("Button_zx8")
        self.temps.clicked.connect(self.Function_Buttonclickz8)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选9')
        self.temps.setObjectName("Button_zx9")
        self.temps.clicked.connect(self.Function_Buttonclickz9)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选10')
        self.temps.setObjectName("Button_zx10")
        self.temps.clicked.connect(self.Function_Buttonclickz10)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选11')
        self.temps.setObjectName("Button_zx11")
        self.temps.clicked.connect(self.Function_Buttonclickz11)
        self.Button_zx.append(self.temps)

        self.temps = QtWidgets.QPushButton('自选12')
        self.temps.setObjectName("Button_zx12")
        self.temps.clicked.connect(self.Function_Buttonclickz12)
        self.Button_zx.append(self.temps)

        self.Button_e0 = QtWidgets.QPushButton('Talib指标条件设置(升级中)')
        self.Button_e0.setObjectName("Button_e0")
        self.Button_e0.clicked.connect(self.Function_Buttonclicke0)

        self.Button_e1 = QtWidgets.QPushButton('自定义指标(升级中)')
        self.Button_e1.setObjectName("Button_e1")
        self.Button_e1.clicked.connect(self.Function_Buttonclicke1)

        self.Button_e2 = QtWidgets.QPushButton('指标条件组合策略(升级中)')
        self.Button_e2.setObjectName("Button_e2")
        self.Button_e2.clicked.connect(self.Function_Buttonclicke2)

        self.Button_e3 = QtWidgets.QPushButton('随机组合生成(升级中)')
        self.Button_e3.setObjectName("Button_e3")
        self.Button_e3.clicked.connect(self.Function_Buttonclicke3)

        self.Button_e4 = QtWidgets.QPushButton('指标自动交易合约选择(升级中)')
        self.Button_e4.setObjectName("Button_e4")
        self.Button_e4.clicked.connect(self.Function_Buttonclicke4)

        self.Button_e5 = QtWidgets.QPushButton('数据统计(升级中)')
        self.Button_e5.setObjectName("Button_e5")
        self.Button_e5.clicked.connect(self.Function_Buttonclicke5)

        self.frame = QtWidgets.QFrame(self.Button_h[0])
        self.frame.setMinimumSize(QtCore.QSize(0, 0))
        self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame.setLineWidth(3)
        self.frame.setObjectName("frame")
        self.verticalLayout.addWidget(self.frame)

        self.gridLayout_optionalstock = QtWidgets.QGridLayout(self.frame)
        self.gridLayout_optionalstock.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_optionalstock.setObjectName("gridLayout_optionalstock")
        self.gridLayout_optionalstock.addWidget(self.Button_h[0], 1, 0, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[1], 1, 1, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[2], 1, 2, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[3], 1, 3, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[4], 1, 4, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[5], 1, 5, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[6], 1, 6, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[7], 1, 7, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[8], 1, 8, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[9], 1, 9, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[10], 1, 10, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_h[11], 1, 11, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[0], 2, 0, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[1], 2, 1, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[2], 2, 2, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[3], 2, 3, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[4], 2, 4, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[5], 2, 5, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[6], 2, 6, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[7], 2, 7, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[8], 2, 8, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[9], 2, 9, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[10], 2, 10, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_t[11], 2, 11, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[0], 3, 0, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[1], 3, 1, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[2], 3, 2, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[3], 3, 3, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[4], 3, 4, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[5], 3, 5, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[6], 3, 6, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[7], 3, 7, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[8], 3, 8, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[9], 3, 9, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[10], 3, 10, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_zx[11], 3, 11, 1, 1)
        self.gridLayout_optionalstock.addWidget(self.Button_e0, 4, 0, 1, 2)
        self.gridLayout_optionalstock.addWidget(self.Button_e1, 4, 2, 1, 2)
        self.gridLayout_optionalstock.addWidget(self.Button_e2, 4, 4, 1, 2)
        self.gridLayout_optionalstock.addWidget(self.Button_e3, 4, 6, 1, 2)
        self.gridLayout_optionalstock.addWidget(self.Button_e4, 4, 8, 1, 2)
        self.gridLayout_optionalstock.addWidget(self.Button_e5, 4, 10, 1, 2)

        geo = self.Button_h[0].geometry()
        geo.moveCenter(self.frame.rect().center())

        self.verticalLayout_2.addWidget(self.frame)
        self.dockWidget1.setWidget(self.dockWidgetContents)
        MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(1), self.dockWidget1)
        self.toolBar = QtWidgets.QToolBar(MainWindow)
        self.toolBar.setObjectName("toolBar")
        MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)
        self.dockWidget2 = QtWidgets.QDockWidget(MainWindow)
        self.dockWidget2.setObjectName("dockWidget2")
        self.dockWidgetContents_2 = QtWidgets.QWidget()
        self.dockWidgetContents_2.setObjectName("dockWidgetContents_2")
        self.gridLayout_3 = QtWidgets.QGridLayout(self.dockWidgetContents_2)
        self.gridLayout_3.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_3.setObjectName("gridLayout_3")
        # 左边行情滚动位置

        self.dockWidget2.setWidget(self.dockWidgetContents_2)
        MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(1), self.dockWidget2)

        # 热力图
        '''
        self.gr_wid = pg.GraphicsLayoutWidget(show=True)
        ## Create image items
        data4 = np.fromfunction(lambda i, j: (1 + 0.3 * np.sin(i)) * (i) ** 2 + (j) ** 2, (100, 100))
        noisy_data = data4 * (1 + 0.2 * np.random.random(data4.shape))
        noisy_transposed = noisy_data.transpose()

        # --- add non-interactive image with integrated color -----------------
        i1 = pg.ImageItem(image=data4)
        p1 = self.gr_wid.addPlot(title="参数优化")
        p1.addItem(i1)
        p1.setMouseEnabled(x=False, y=False)
        p1.disableAutoRange()
        # p1.hideButtons()
        p1.setRange(xRange=(0, 100), yRange=(0, 100), padding=0)
        for key in ['left', 'right', 'top', 'bottom']:
            p1.showAxis(key)
            axis = p1.getAxis(key)
            axis.setZValue(1)
            if key in ['top', 'right']:
                p1.getAxis(key).setStyle(showValues=False)

        cmap = pg.colormap.get('CET-L9')
        bar = pg.ColorBarItem(
            interactive=False, values=(0, 30_000), cmap=cmap,
            label='vertical fixed color bar'
        )
        bar.setImageItem(i1, insert_in=p1)

        # manually adjust reserved space at top and bottom to align with plot
        bar.getAxis('bottom').setHeight(21)
        bar.getAxis('top').setHeight(31)
        self.gr_wid.addItem(bar, 0, 2, 2, 1)  # large bar spanning both rows

        # self.verticalLayout.addWidget(self.gr_wid)
        self.gridLayout_3.addWidget(self.gr_wid, 0, 0, 1, 1)
        # self.win.showMaximized()
        '''
        # 热力图

        # TAB2 回测资金曲线位置
        self.win5 = pg.GraphicsLayoutWidget(show=True)
        self.win5.setWindowTitle('资金曲线')
        self.plt_backtesting = self.win5.addPlot(title="资金曲线")
        # self.win.setBackground('y')
        # plt_backtesting.setAutoVisibleOnly(y=True)
        self.curve_backtesting = self.plt_backtesting.plot(pen='y')
        self.plt_backtesting.setMouseEnabled(x=False, y=False)  # 禁用轴操作
        self.gridLayout_3.addWidget(self.win5, 1, 0, 1, 1)
        self.win5.showMaximized()
        # TAB2 回测资金曲线位置

        self.Button_OpenDll = QtWidgets.QAction(MainWindow, checkable=True)
        self.Button_OpenDll.setObjectName("Button_OpenDll")
        self.Button_CloseDll = QtWidgets.QAction(MainWindow, checkable=True)
        self.Button_CloseDll.setObjectName("Button_CloseDll")
        self.Button_StrategyManage_SingleThread = QtWidgets.QAction(MainWindow, checkable=True)
        self.Button_StrategyManage_SingleThread.setObjectName("Button_StrategyManage_SingleThread")
        self.Button_StrategyManage_MulitProcess = QtWidgets.QAction(MainWindow, checkable=True)
        self.Button_StrategyManage_MulitProcess.setObjectName("Button_StrategyManage_MulitProcess")
        self.Button_KlineSource_RealTimeTick = QtWidgets.QAction(MainWindow, checkable=True)
        self.Button_KlineSource_RealTimeTick.setObjectName("Button_KlineSource_RealTimeTick")
        self.Button_KlineSource_ServerToday = QtWidgets.QAction(MainWindow, checkable=True)
        self.Button_KlineSource_ServerToday.setObjectName("Button_KlineSource_ServerToday")
        self.Button_KlineSource_ServerMultiday = QtWidgets.QAction(MainWindow, checkable=True)
        self.Button_KlineSource_ServerMultiday.setObjectName("Button_KlineSource_ServerMultiday")
        self.Button_CloseDll.setChecked(True)
        self.Button_StrategyManage_SingleThread.setChecked(True)
        # self.Button_KlineSource_RealTimeTick.setChecked(True)

        self.Navgiate1 = QtWidgets.QAction(MainWindow)
        self.Navgiate1.setObjectName("Navgiate1")
        self.Navgiate2 = QtWidgets.QAction(MainWindow)
        self.Navgiate2.setObjectName("Navgiate2")
        self.Navgiate3 = QtWidgets.QAction(MainWindow)
        self.Navgiate3.setObjectName("Navgiate3")
        self.Navgiate4 = QtWidgets.QAction(MainWindow)
        self.Navgiate4.setObjectName("Navgiate4")
        self.Navgiate5 = QtWidgets.QAction(MainWindow)
        self.Navgiate5.setObjectName("Navgiate5")
        self.Navgiate6 = QtWidgets.QAction(MainWindow)
        self.Navgiate6.setObjectName("Navgiate6")
        self.Navgiate7 = QtWidgets.QAction(MainWindow)
        self.Navgiate7.setObjectName("Navgiate7")
        self.Navgiate8 = QtWidgets.QAction(MainWindow)
        self.Navgiate8.setObjectName("Navgiate8")
        self.Navgiate1_C = QtWidgets.QAction(MainWindow)
        self.Navgiate1_C.setObjectName("Navgiate1_C")
        self.menuSubmenu_2.addAction(self.Navgiate2)
        self.menuSubmenu_2.addAction(self.Navgiate1_C)
        self.menuMenu_nav1.addAction(self.Button_OpenDll)
        self.menuMenu_nav1.addAction(self.Button_CloseDll)

        self.menuMenu_nav2.addAction(self.Button_StrategyManage_SingleThread)
        self.menuMenu_nav2.addAction(self.Button_StrategyManage_MulitProcess)

        self.menuMenu_nav3.addAction(self.Button_KlineSource_RealTimeTick)
        self.menuMenu_nav3.addAction(self.Button_KlineSource_ServerToday)
        self.menuMenu_nav3.addAction(self.Button_KlineSource_ServerMultiday)

        # self.menuMenu.addAction(self.menuSubmenu_2.menuAction())
        self.menubar.addAction(self.menuMenu_nav1.menuAction())
        self.menubar.addAction(self.menuMenu_nav2.menuAction())
        self.menubar.addAction(self.menuMenu_nav3.menuAction())

        # self.menuMenu.addAction(self.Navgiate1)
        # self.menuMenu.addAction(self.menuSubmenu_2.menuAction())
        # self.menubar.addAction(self.menuMenu.menuAction())

        self.toolBar.addAction(self.Navgiate1)
        self.toolBar.addAction(self.Navgiate2)
        self.toolBar.addAction(self.Navgiate3)
        self.toolBar.addAction(self.Navgiate4)
        self.toolBar.addAction(self.Navgiate5)
        self.toolBar.addAction(self.Navgiate6)
        self.toolBar.addAction(self.Navgiate7)
        self.toolBar.addAction(self.Navgiate8)
        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)
        self.toolBox1.setCurrentIndex(1)
        self.toolBox2.setCurrentIndex(1)
        self.tabWidget_2.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        # MainWindow.setTabOrder(self.pushButton, self.checkableButton)
        # MainWindow.setTabOrder(self.checkableButton, self.pushButton_5)
        # MainWindow.setTabOrder(self.pushButton_5, self.tabWidget_2)
        MainWindow.setTabOrder(self.tabWidget_2, self.table_account)
        # MainWindow.setTabOrder(self.tabWidget, self.table_strategy)
        MainWindow.setTabOrder(self.table_account, self.radioButton)
        MainWindow.setTabOrder(self.radioButton, self.checkBox)
        MainWindow.setTabOrder(self.checkBox, self.checkBox_2)
        MainWindow.setTabOrder(self.checkBox_2, self.treeWidget)
        MainWindow.setTabOrder(self.treeWidget, self.Button_Start)
        # MainWindow.setTabOrder(self.Button_Start, self.menu_a_popup)
        # MainWindow.setTabOrder(self.menu_a_popup, self.menu_b_popup)
        # MainWindow.setTabOrder(self.menu_b_popup, self.menu_c_popup)
        # MainWindow.setTabOrder(self.menu_c_popup, self.Button_Stop)
        # MainWindow.setTabOrder(self.Button_Stop, self.doubleSpinBox)
        # MainWindow.setTabOrder(self.doubleSpinBox, self.toolButton)
        MainWindow.setTabOrder(self.toolButton, self.comboBox_kline)
        MainWindow.setTabOrder(self.toolButton, self.comboBox_exchange)
        MainWindow.setTabOrder(self.toolButton, self.comboBox_instrument)
        MainWindow.setTabOrder(self.toolButton, self.comboBox_instrumentid)

        # 左边行情滚动位置
        # MainWindow.setTabOrder(self.comboBox, self.horizontalSlider)
        # MainWindow.setTabOrder(self.horizontalSlider, self.textEdit)
        # 左边行情滚动位置
        # MainWindow.setTabOrder(self.textEdit, self.verticalSlider)
        # MainWindow.setTabOrder(self.verticalSlider, self.tabWidget)

        # 1，1 委托记录
        # MainWindow.setTabOrder(self.tabWidget, self.lineEdit)
        # MainWindow.setTabOrder(self.lineEdit, self.listWidget)

    # 更新回测资金曲线
    def updatebacktestingUi(self, newdata):
        def update_backtesting(newdata):
            global data_backtesting, count
            data_backtesting.append(newdata)
            if len(data_backtesting) > 100:
                data_backtesting.pop(0)
            self.curve_backtesting.setData(np.hstack(data_backtesting))
            count += 1

        for i in range(101):
            update_backtesting(newdata)

    # 从文件读取更新当日K线图
    def UpdateKlineUIFromFile(self, InstrumentID, TradingDay):
        try:
            global kid, count
            kid = 1
            fname = globalvar.currpath + "\\data_today\\" + InstrumentID + ".csv"
            print('filename: ' + fname)
            globalvar.ticklist = []
            if os.path.isfile(fname):
                for line in open(fname):
                    ld = line.split(',')
                    temp = (kid,
                            float(ld[0]),
                            float(ld[1]),
                            float(ld[3]),
                            float(ld[4]),
                            float(ld[5]),
                            float(ld[6]))
                    globalvar.data_kline_M1.append(temp)

                    tempstr = str(int(float(ld[1]) * 10000))
                    tempstr_list = list(tempstr)
                    tempstr_list.insert(len(tempstr_list) - 2, ':')
                    tempstr = ''.join(tempstr_list)
                    globalvar.ticklist.append(ld[0] + "\n" + tempstr)

                    '''
                    globalvar.dict_dataframe_kline_M1[InstrumentID] = pd.DataFrame(
                        {'datetime': [],'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [], 'close': [], 'low': [], 'high': [],
                         'vol': []}, index=[])
                    '''
                    ld[1] = ld[1].ljust(8, '0')
                    ld[1] = '{:0>8s}'.format(ld[1])
                    tdatetime = ld[0][0:4] + "-" + ld[0][4:6] + "-" + ld[0][6:8] + " " + ld[1][2:4] + ":" + ld[1][
                                                                                                            4:6] + ":" + \
                                ld[1][6:8]
                    globalvar.dict_dataframe_kline_M1[InstrumentID] = globalvar.dict_dataframe_kline_M1[
                        InstrumentID].append({
                        'datetime': tdatetime,
                        'recordid': '{:0>8s}'.format(str(kid)),
                        'tradingday': ld[0],
                        'klinetime': ld[1],
                        'instrumentid': ld[2],
                        'open': float(ld[3]),
                        'close': float(ld[4]),
                        'low': float(ld[5]),
                        'high': float(ld[6]),
                        'vol': float(ld[7]),
                    }, ignore_index=True)
                    kid = kid + 1
            self.plt_kline.removeItem(self.item)

            self.item = CandlestickItem(globalvar.data_kline_M1)  # 原始数据,对应（0,0）幅图
            try:
                self.plt_kline.addItem(self.item)
                count += 1
            except Exception as e:
                print("UpdateKlineUIFromFileB Error:" + repr(e))

            # 横坐标刻度
            xax = self.plt_kline.getAxis('bottom')  # 坐标轴x
            xdict = dict(enumerate(globalvar.ticklist))
            xax.setTicks([xdict.items()])

            # 根据M1周期K线合成M3周期K线数据
            # entry_combinekline.ComposeKlineUpdate(InstrumentID, "3min")


        except Exception as e:
            print("UpdateKlineUIFromFile Error:" + repr(e))

    def UpdateKlineUIFromFileBakUp(self, InstrumentID, TradingDay):
        try:
            global kid, count
            kid = 1
            fname = globalvar.currpath + "\\data_today\\" + InstrumentID + ".csv"
            print('filename: ' + fname)
            globalvar.ticklist = []
            if os.path.isfile(fname):
                for line in open(fname):
                    ld = line.split(',')
                    temp = (kid,
                            float(ld[0]),
                            float(ld[1]),
                            float(ld[3]),
                            float(ld[4]),
                            float(ld[5]),
                            float(ld[6]))
                    globalvar.data_kline_M1.append(temp)

                    tempstr = str(int(float(ld[1]) * 10000))
                    tempstr_list = list(tempstr)
                    tempstr_list.insert(len(tempstr_list) - 2, ':')
                    tempstr = ''.join(tempstr_list)
                    globalvar.ticklist.append(ld[0] + "\n" + tempstr)

                    '''
                    globalvar.dict_dataframe_kline_M1[InstrumentID] = pd.DataFrame(
                        {'datetime': [],'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [], 'close': [], 'low': [], 'high': [],
                         'vol': []}, index=[])
                    '''
                    ld[1] = ld[1].ljust(8, '0')
                    ld[1] = '{:0>8s}'.format(ld[1])
                    tdatetime = ld[0][0:4] + "-" + ld[0][4:6] + "-" + ld[0][6:8] + " " + ld[1][2:4] + ":" + ld[1][
                                                                                                            4:6] + ":" + \
                                ld[1][6:8]
                    globalvar.dict_dataframe_kline_M1[InstrumentID] = globalvar.dict_dataframe_kline_M1[
                        InstrumentID].append({
                        'datetime': tdatetime,
                        'recordid': '{:0>8s}'.format(str(kid)),
                        'tradingday': ld[0],
                        'klinetime': ld[1],
                        'instrumentid': ld[2],
                        'open': float(ld[3]),
                        'close': float(ld[4]),
                        'low': float(ld[5]),
                        'high': float(ld[6]),
                        'vol': float(ld[7]),
                    }, ignore_index=True)
                    kid = kid + 1
            self.plt_kline.removeItem(self.item)

            self.item = CandlestickItem(globalvar.data_kline_M1)  # 原始数据,对应（0,0）幅图
            try:
                self.plt_kline.addItem(self.item)
                count += 1
            except Exception as e:
                print("UpdateKlineUIFromFileB Error:" + repr(e))

            # 横坐标刻度
            xax = self.plt_kline.getAxis('bottom')  # 坐标轴x
            xdict = dict(enumerate(globalvar.ticklist))
            xax.setTicks([xdict.items()])

            # 根据M1周期K线合成M3周期K线数据
            # entry_combinekline.ComposeKlineUpdate(InstrumentID, "3min")


        except Exception as e:
            print("UpdateKlineUIFromFile Error:" + repr(e))

    def dateprevious(self, year, mouth, day):
        list_mouth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        if day == 1:
            if mouth == 1:
                year = year - 1
                mouth = 12
                day = list_mouth[mouth - 1]
            else:
                mouth = mouth - 1
                day = list_mouth[mouth - 1]
                if day == 28:
                    if year % 4 == 0:
                        day = 29
        else:
            day = day - 1
        return year * 10000 + mouth * 100 + day

    # 从文件读取更新多日M1 K线图
    def UpdateMultiKlineUIFromFile(self, InstrumentID, TradingDay):
        global kid
        kid = 1
        TradingDaylist = []
        globalvar.ticklist = []
        newTradingDay = TradingDay
        for addday in range(10):
            tyear = int(str(newTradingDay)[0:4])
            tmonth = int(str(newTradingDay)[4:6])
            tday = int(str(newTradingDay)[6:8])
            newTradingDay = self.dateprevious(tyear, tmonth, tday)
            TradingDaylist.append(newTradingDay)
        TradingDaylist.reverse()
        for addday in range(10):
            fname = globalvar.currpath + "\\data_multiday\\" + InstrumentID + "\\" + str(
                TradingDaylist[addday]) + ".csv"
            if os.path.isfile(fname):
                for line in open(fname):
                    # print(line)
                    ld = line.split(',')
                    temp = (kid,
                            float(ld[0]),
                            float(ld[1]),
                            float(ld[3]),
                            float(ld[4]),
                            float(ld[5]),
                            float(ld[6]))
                    globalvar.data_kline_M1.append(temp)

                    tempstr = str(int(float(ld[1]) * 10000))
                    tempstr_list = list(tempstr)
                    tempstr_list.insert(len(tempstr_list) - 2, ':')
                    tempstr = ''.join(tempstr_list)
                    globalvar.ticklist.append(ld[0] + "\n" + tempstr)

                    '''
                    globalvar.dict_dataframe_kline_M1[InstrumentID] = pd.DataFrame(
                        {'datetime': [],'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [], 'close': [], 'low': [], 'high': [],
                         'vol': []}, index=[])
                    '''
                    ld[1] = ld[1].ljust(8, '0')
                    ld[1] = '{:0>8s}'.format(ld[1])
                    tdatetime = ld[0][0:4] + "-" + ld[0][4:6] + "-" + ld[0][6:8] + " " + ld[1][2:4] + ":" + ld[1][
                                                                                                            4:6] + ":" + \
                                ld[1][6:8]
                    globalvar.dict_dataframe_kline_M1[InstrumentID] = globalvar.dict_dataframe_kline_M1[
                        InstrumentID].append({
                        'datetime': tdatetime,
                        # 'recordid': ld[0] + str(kid),
                        'recordid': '{:0>8s}'.format(str(kid)),
                        'tradingday': ld[0],
                        'klinetime': ld[1],
                        'instrumentid': ld[2],
                        'open': float(ld[3]),
                        'close': float(ld[4]),
                        'low': float(ld[5]),
                        'high': float(ld[6]),
                        'vol': float(ld[7]),
                    }, ignore_index=True)

                    kid = kid + 1
        fname = globalvar.currpath + "\\data_multiday\\" + InstrumentID + "\\" + str(TradingDay) + ".csv"

        if os.path.isfile(fname):
            for line in open(fname):
                # print(line)
                ld = line.split(',')
                temp = (kid,
                        float(ld[0]),
                        float(ld[1]),
                        float(ld[3]),
                        float(ld[4]),
                        float(ld[5]),
                        float(ld[6]))
                globalvar.data_kline_M1.append(temp)

                tempstr = str(int(float(ld[1]) * 10000))
                tempstr_list = list(tempstr)
                tempstr_list.insert(len(tempstr_list) - 2, ':')
                tempstr = ''.join(tempstr_list)

                globalvar.ticklist.append(ld[0] + "\n" + tempstr)

                '''
                globalvar.dict_dataframe_kline_M1[InstrumentID] = pd.DataFrame(
                    {'datetime': [],'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [], 'close': [], 'low': [], 'high': [],
                     'vol': []}, index=[])
                '''

                ld[1] = ld[1].ljust(8, '0')
                ld[1] = '{:0>8s}'.format(ld[1])
                tdatetime = ld[0][0:4] + "-" + ld[0][4:6] + "-" + ld[0][6:8] + " " + ld[1][2:4] + ":" + ld[1][
                                                                                                        4:6] + ":" + ld[
                                                                                                                         1][
                                                                                                                     6:8]
                globalvar.dict_dataframe_kline_M1[InstrumentID] = globalvar.dict_dataframe_kline_M1[
                    InstrumentID].append({
                    'datetime': tdatetime,
                    'recordid': '{:0>8s}'.format(str(kid)),
                    'tradingday': ld[0],
                    'klinetime': ld[1],
                    'instrumentid': ld[2],
                    'open': float(ld[3]),
                    'close': float(ld[4]),
                    'low': float(ld[5]),
                    'high': float(ld[6]),
                    'vol': float(ld[7]),
                }, ignore_index=True)

                kid = kid + 1
        self.plt_kline.removeItem(self.item)
        self.item = CandlestickItem(globalvar.data_kline_M1)  # 原始数据,对应（0,0）幅图
        # npdata = np.array(globalvar.data_kline_M1)
        try:
            self.plt_kline.addItem(self.item)
            count += 1
        except Exception as e:
            print("UpdateMultiKlineUIFromFile Error:" + repr(e))
        # globalvar.dict_data_kline_M1[InstrumentID] = globalvar.data_kline_M1.copy()

        # 横坐标刻度
        xax = self.plt_kline.getAxis('bottom')  # 坐标轴x
        xdict = dict(enumerate(globalvar.ticklist))
        xax.setTicks([xdict.items()])

        # 根据M1周期K线合成M3周期K线数据
        # entry_combinekline.ComposeKlineUpdate(InstrumentID, "3min")

    # 更新K线图
    def updateklineUi(self, InstrumentID):
        def update_kline(InstrumentID):
            global lasttime, kid
            global count
            if globalvar.md:
                try:
                    if lasttime != globalvar.md.GetKline(InstrumentID, 1).contents.KlineTime:
                        # if len(globalvar.data_kline_M1)==0:
                        #        self.plt_kline.clear()
                        # print('update_kline: ' + str(InstrumentID, encoding="utf-8"))
                        lasttime = globalvar.md.GetKline(InstrumentID, 1).contents.KlineTime
                        # 数据对应关系 ( id, TradingDay, KlineTime,  open, close, min, max).
                        temp = (kid,
                                globalvar.md.GetKline(InstrumentID, 1).contents.TradingDay,
                                globalvar.md.GetKline(InstrumentID, 1).contents.KlineTime,
                                globalvar.md.GetKline(InstrumentID, 1).contents.Open,
                                globalvar.md.GetKline(InstrumentID, 1).contents.Close,
                                globalvar.md.GetKline(InstrumentID, 1).contents.Low,
                                globalvar.md.GetKline(InstrumentID, 1).contents.High)
                        globalvar.data_kline_M1.append(temp)

                        tempstr = str(int(float(lasttime) * 10000))
                        tempstr_list = list(tempstr)
                        tempstr_list.insert(len(tempstr_list) - 2, ':')
                        tempstr = ''.join(tempstr_list)

                        globalvar.ticklist.append(
                            globalvar.md.GetKline(InstrumentID, 1).contents.TradingDay + "\n" + tempstr)

                        ld0 = globalvar.md.GetKline(InstrumentID, 1).contents.TradingDa
                        ld1 = globalvar.md.GetKline(InstrumentID, 1).contents.KlineTime
                        ld1 = ld1.ljust(8, '0')
                        ld1 = '{:0>8s}'.format(ld1)
                        tdatetime = ld0[0:4] + "-" + ld0[4:6] + "-" + ld0[6:8] + " " + ld1[2:4] + ":" + ld1[
                                                                                                        4:6] + ":" + ld1[
                                                                                                                     6:8]
                        globalvar.dict_dataframe_kline_M1[InstrumentID] = globalvar.dict_dataframe_kline_M1[
                            InstrumentID].append({
                            'datetime': tdatetime,
                            'recordid': '{:0>8s}'.format(str(kid)),
                            'tradingday': globalvar.md.GetKline(InstrumentID, 1).contents.TradingDay,
                            'klinetime': globalvar.md.GetKline(InstrumentID, 1).contents.KlineTime,
                            'instrumentid': globalvar.md.GetKline(InstrumentID, 1).contents.InstrumentID,
                            'open': float(globalvar.md.GetKline(InstrumentID, 1).contents.Open),
                            'close': float(globalvar.md.GetKline(InstrumentID, 1).contents.Close),
                            'low': float(globalvar.md.GetKline(InstrumentID, 1).contents.Low),
                            'high': float(globalvar.md.GetKline(InstrumentID, 1).contents.High),
                            'vol': int(globalvar.md.GetKline(InstrumentID, 1).contents.Vol),
                        }, ignore_index=True)

                        kid = kid + 1
                        for k in globalvar.data_kline_M1:
                            print(str(k))
                        self.plt_kline.removeItem(self.item)
                        self.item = CandlestickItem(globalvar.data_kline_M1)  # 原始数据,对应（0,0）幅图
                        # npdata = np.array(globalvar.data_kline_M1)
                        try:
                            self.plt_kline.addItem(self.item)
                            count += 1
                        except Exception as e:
                            print("update_kline Error:" + repr(e))
                        # globalvar.dict_data_kline_M1[InstrumentID] = globalvar.data_kline_M1.copy()

                        # 横坐标刻度
                        xax = self.plt_kline.getAxis('bottom')  # 坐标轴x
                        xdict = dict(enumerate(globalvar.ticklist))
                        xax.setTicks([xdict.items()])
                        self.Background_klineperiod()
                except Exception as e:
                    print("update_kline Error:" + repr(e))

        update_kline(InstrumentID)

    # 更新分时图
    def updatemarketUi(self, newdata):
        def update_market(newdata):
            global data_market, count
            data_market.append(newdata)
            if len(data_market) > 1000:
                data_market.pop(0)
            self.curve_market.setData(np.hstack(data_market))
            count += 1

        update_market(newdata)

    global lastTradingDay
    lastTradingDay = ''

    # 更新实时资金曲线
    def updaterealtimecurveUi(self, newdata, TradingDay):
        def update_realtime(newdata):
            global data_realtimecurve, count, lastTradingDay
            data_realtimecurve.append(newdata)
            # if len(data_realtimecurve) > 100:
            if TradingDay != lastTradingDay:
                lastTradingDay = TradingDay
                data_realtimecurve.pop(0)
            else:
                self.curve_realtime.setData(np.hstack(data_realtimecurve))
            count += 1

        update_realtime(newdata)

    def fileTime(self, file):
        return [time.ctime(os.path.getatime(file)), time.ctime(os.path.getctime(file)),
                time.ctime(os.path.getmtime(file))]

    global dict_strategy, dict_strategyrun
    dict_strategy = {}
    dict_strategyrun = {}

    # 多进程模式，由C++回调调用Python策略,支持文件类型：（1）.py（2）.dll
    def function_scanstrategy_MulitProcess(self):
        path = "strategyfile"
        ls = os.listdir(path)
        for i in ls:
            c_path = os.path.join(path, i)
            if os.path.isdir(c_path):
                print(c_path)
                self.ClearPath(c_path)
            else:
                file = os.path.splitext(c_path)
                filename, type = file
                if type == ".py" or type == ".pyd" or type == ".pyc":
                    if c_path in dict_strategy:
                        if dict_strategy[c_path] != self.fileTime(c_path):
                            print("修改了")
                    else:
                        try:
                            filenameini = c_path
                            filenameini = filenameini.replace('py', 'ini')
                            #  实例化configParser对象
                            config = configparser.ConfigParser()
                            # -read读取ini文件
                            config.read(filenameini, encoding='utf-8')
                            if config.getint('setting', 'run') == 1:
                                dict_strategyrun[c_path] = 1
                            else:
                                dict_strategyrun[c_path] = 0
                            dict_strategy[c_path] = self.fileTime(c_path)
                            # print("find Strategy file:", c_path,self.fileTime(c_path))
                            row_cnt = self.table_strategy.rowCount()  # 返回当前行数（尾部）
                            # print("列数：",row_cnt)
                            self.table_strategy.insertRow(row_cnt)  # 尾部插入一行新行表格
                            column_cnt = self.table_strategy.columnCount()  # 返回当前列数
                            # for column in range(column_cnt):
                            item = QTableWidgetItem(str(row_cnt + 1))
                            if dict_strategyrun[c_path] == 1:
                                item.setCheckState(QtCore.Qt.Checked)
                            else:
                                item.setCheckState(QtCore.Qt.Unchecked)
                            self.table_strategy.setItem(row_cnt, 0, item)
                            item = QTableWidgetItem(str("策略"))
                            self.table_strategy.setItem(row_cnt, 1, item)
                            item = QTableWidgetItem(str(c_path))
                            self.table_strategy.setItem(row_cnt, 2, item)
                            self.table_strategy.setItem(row_cnt, 3, item)
                            self.table_strategy.setItem(row_cnt, 4, item)
                            self.table_strategy.setItem(row_cnt, 5, item)
                        except:
                            pass

                        # item2 = QtWidgets.QTableWidgetItem("1")
                        # item.setCheckState(QtCore.Qt.Unchecked)
                        # self.table_strategy.setItem(0, 0, item2)

                        # column_cnt = self.table_strategy.columnCount()  # 返回当前列数
                        # item = QtWidgets.table_strategy()
                        # self.table_strategy.setVerticalHeaderItem(1, item)

        try:
            for k in dict_strategy:
                print("(%s) %s" % (dict_strategy.index(k) + 1, k))
        except Exception as e:
            print("function_scanstrategy Error:" + repr(e))

    # 单线程由Python直接驱动策略, 支持文件类型：（1）.py
    def function_scanstrategy_SingleThreadPyManage(self):
        path = "strategyfile"
        ls = os.listdir(path)
        for i in ls:
            c_path = os.path.join(path, i)
            if os.path.isdir(c_path):
                print(c_path)
                self.ClearPath(c_path)
            else:
                file = os.path.splitext(c_path)
                filename, type = file
                if type == ".py" or type == ".pyd" or type == ".pyc":
                    if c_path in dict_strategy:
                        if dict_strategy[c_path] != self.fileTime(c_path):
                            print("修改了")
                    else:
                        try:
                            filenameini = c_path
                            filenameini = filenameini.replace('py', 'ini')
                            #  实例化configParser对象
                            config = configparser.ConfigParser()
                            # -read读取ini文件
                            config.read(filenameini, encoding='utf-8')
                            if config.getint('setting', 'run') == 1:
                                dict_strategyrun[c_path] = 1
                            else:
                                dict_strategyrun[c_path] = 0
                            dict_strategy[c_path] = self.fileTime(c_path)
                            # print("find Strategy file:", c_path,self.fileTime(c_path))
                            row_cnt = self.table_strategy.rowCount()  # 返回当前行数（尾部）
                            # print("列数：",row_cnt)
                            self.table_strategy.insertRow(row_cnt)  # 尾部插入一行新行表格
                            column_cnt = self.table_strategy.columnCount()  # 返回当前列数
                            # for column in range(column_cnt):
                            item = QTableWidgetItem(str(row_cnt + 1))
                            if dict_strategyrun[c_path] == 1:
                                item.setCheckState(QtCore.Qt.Checked)
                            else:
                                item.setCheckState(QtCore.Qt.Unchecked)
                            self.table_strategy.setItem(row_cnt, 0, item)
                            item = QTableWidgetItem(str("策略"))
                            self.table_strategy.setItem(row_cnt, 1, item)
                            item = QTableWidgetItem(str(c_path))
                            self.table_strategy.setItem(row_cnt, 2, item)
                            self.table_strategy.setItem(row_cnt, 3, item)
                            self.table_strategy.setItem(row_cnt, 4, item)
                            self.table_strategy.setItem(row_cnt, 5, item)
                        except:
                            pass

                        # item2 = QtWidgets.QTableWidgetItem("1")
                        # item.setCheckState(QtCore.Qt.Unchecked)
                        # self.table_strategy.setItem(0, 0, item2)

                        # column_cnt = self.table_strategy.columnCount()  # 返回当前列数
                        # item = QtWidgets.table_strategy()
                        # self.table_strategy.setVerticalHeaderItem(1, item)

        try:
            for k in dict_strategy:
                print("(%s) %s" % (dict_strategy.index(k) + 1, k))
        except Exception as e:
            print("function_scanstrategy Error:" + repr(e))

    # 策略管理器模式
    def function_scanstrategy(self):
        if 1:
            self.function_scanstrategy_SingleThreadPyManage()
        else:
            self.function_scanstrategy_MulitProcess()

    def function_scanmdhistorylog(self):
        path = "log\\md"
        ls = os.listdir(path)
        for i in ls:
            c_path = os.path.join(path, i)
            if os.path.isdir(c_path):
                print(c_path)
                self.ClearPath(c_path)
            else:
                file = os.path.splitext(c_path)
                filename, type = file
                if type == ".txt":

                    if c_path in dict_strategy:
                        if dict_strategy[c_path] != self.fileTime(c_path):
                            print("修改了")
                    else:
                        '''
                        filenameini = c_path
                        filenameini=filenameini.replace('py','ini')
                        #  实例化configParser对象
                        config = configparser.ConfigParser()
                        # -read读取ini文件
                        config.read(filenameini,encoding='utf-8')
                        if config.getint('setting', 'run')==1:
                            dict_strategyrun[c_path] = 1
                        else:
                            dict_strategyrun[c_path] = 0
                        '''
                        dict_strategy[c_path] = self.fileTime(c_path)
                        # print("find Strategy file:", c_path,self.fileTime(c_path))
                        row_cnt = self.table_historymd.rowCount()  # 返回当前行数（尾部）
                        # print("列数：",row_cnt)
                        self.table_historymd.insertRow(row_cnt)  # 尾部插入一行新行表格
                        column_cnt = self.table_historymd.columnCount()  # 返回当前列数
                        # for column in range(column_cnt):
                        item = QTableWidgetItem(str(row_cnt + 1))

                        # if dict_strategyrun[c_path] == 1:
                        #    item.setCheckState(QtCore.Qt.Checked)
                        # else:
                        #    item.setCheckState(QtCore.Qt.Unchecked)

                        self.table_historymd.setItem(row_cnt, 0, item)
                        item = QTableWidgetItem(str("策略"))
                        self.table_historymd.setItem(row_cnt, 1, item)
                        item = QTableWidgetItem(str(c_path))
                        self.table_historymd.setItem(row_cnt, 2, item)
                        self.table_historymd.setItem(row_cnt, 3, item)
                        self.table_historymd.setItem(row_cnt, 4, item)
                        self.table_historymd.setItem(row_cnt, 5, item)

                        # item2 = QtWidgets.QTableWidgetItem("1")
                        # item.setCheckState(QtCore.Qt.Unchecked)
                        # self.table_historymd.setItem(0, 0, item2)

                    # column_cnt = self.table_historymd.columnCount()  # 返回当前列数
                    # item = QtWidgets.table_historymd()
                    # self.table_historymd.setVerticalHeaderItem(1, item)

    def function_scantdhistorylog(self):
        path = "log\\td"
        ls = os.listdir(path)
        for i in ls:
            c_path = os.path.join(path, i)
            if os.path.isdir(c_path):
                print(c_path)
                self.ClearPath(c_path)
            else:
                file = os.path.splitext(c_path)
                filename, type = file
                if type == ".txt":

                    if c_path in dict_strategy:
                        if dict_strategy[c_path] != self.fileTime(c_path):
                            print("修改了")
                    else:
                        '''
                        filenameini = c_path
                        filenameini=filenameini.replace('py','ini')
                        #  实例化configParser对象
                        config = configparser.ConfigParser()
                        # -read读取ini文件
                        config.read(filenameini,encoding='utf-8')
                        if config.getint('setting', 'run')==1:
                            dict_strategyrun[c_path] = 1
                        else:
                            dict_strategyrun[c_path] = 0
                        '''
                        dict_strategy[c_path] = self.fileTime(c_path)
                        # print("find Strategy file:", c_path,self.fileTime(c_path))
                        row_cnt = self.table_historytd.rowCount()  # 返回当前行数（尾部）
                        # print("列数：",row_cnt)
                        self.table_historytd.insertRow(row_cnt)  # 尾部插入一行新行表格
                        column_cnt = self.table_historytd.columnCount()  # 返回当前列数
                        # for column in range(column_cnt):
                        item = QTableWidgetItem(str(row_cnt + 1))

                        # if dict_strategyrun[c_path] == 1:
                        #    item.setCheckState(QtCore.Qt.Checked)
                        # else:
                        #    item.setCheckState(QtCore.Qt.Unchecked)

                        self.table_historytd.setItem(row_cnt, 0, item)
                        item = QTableWidgetItem(str("策略"))
                        self.table_historytd.setItem(row_cnt, 1, item)
                        item = QTableWidgetItem(str(c_path))
                        self.table_historytd.setItem(row_cnt, 2, item)
                        self.table_historytd.setItem(row_cnt, 3, item)
                        self.table_historytd.setItem(row_cnt, 4, item)
                        self.table_historytd.setItem(row_cnt, 5, item)

                        # item2 = QtWidgets.QTableWidgetItem("1")
                        # item.setCheckState(QtCore.Qt.Unchecked)
                        # self.table_historytd.setItem(0, 0, item2)

                    # column_cnt = self.table_historytd.columnCount()  # 返回当前列数
                    # item = QtWidgets.table_historytd()
                    # self.table_historytd.setVerticalHeaderItem(1, item)

    # 打开策略目录
    def Function_OpenStrategyPath(self):
        cur_dir = QDir.currentPath() + "/strategyfile"
        os.startfile(cur_dir)

    # 打开回测报告目录
    def Function_OpenBackTestingPath(self):
        cur_dir = QDir.currentPath() + "/backtesting"
        os.startfile(cur_dir)

    # 清空今日行情日志
    def Function_ClearTodayMdLog(self):
        # self.ClearPath("log/md")
        self.table_listmdlog.clear()
        pass

    # 清空今日交易日志
    def Function_ClearTodayTdLog(self):
        # self.ClearPath("log/md")
        self.table_listtdlog.clear()
        pass

    # 打开算法交易目录
    def Function_OpenAlgorithmicTradingPath(self):
        cur_dir = QDir.currentPath() + "/AlgorithmicTrading"
        os.startfile(cur_dir)

    # 扫描交易历史日志
    def Function_ScanTdLog(self):
        path = "log"
        ls = os.listdir(path)
        for i in ls:
            c_path = os.path.join(path, i)
            if os.path.isdir(c_path):
                print(c_path)
                self.ClearPath(c_path)
            else:
                file = os.path.splitext(c_path)
                filename, type = file
                if type == ".py" or type == ".pyd" or type == ".pyc":
                    print("find log file:", c_path)
                    # item = QtWidgets.table_strategy()
                    # self.table_strategy.setVerticalHeaderItem(1, item)

    # 扫描行情历史日志
    def Function_ScanMdLog(self):
        path = "log"
        ls = os.listdir(path)
        for i in ls:
            c_path = os.path.join(path, i)
            if os.path.isdir(c_path):
                print(c_path)
                self.ClearPath(c_path)
            else:
                file = os.path.splitext(c_path)
                filename, type = file
                if type == ".py" or type == ".pyd" or type == ".pyc":
                    print("find log file:", c_path)
                    # item = QtWidgets.table_strategy()
                    # self.table_strategy.setVerticalHeaderItem(1, item)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        # 交易信息
        self.groupBox.setTitle(_translate("MainWindow", ""))
        self.toolBox1.setItemText(self.toolBox1.indexOf(self.page_order), _translate("MainWindow", "委托记录"))
        self.toolBox2.setItemText(self.toolBox2.indexOf(self.page_instrument), _translate("MainWindow", "合约参数"))
        self.toolBox1.setItemText(self.toolBox1.indexOf(self.page_trade), _translate("MainWindow", "交易记录"))
        self.toolBox2.setItemText(self.toolBox2.indexOf(self.page_position), _translate("MainWindow", "全部持仓/策略持仓"))
        # self.checkableButton.setText(_translate("MainWindow", "Checkable button"))
        # self.pushButton.setText(_translate("MainWindow", "PushButton"))
        # self.pushButton_5.setText(_translate("MainWindow", "PushButton"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_strategy), _translate("MainWindow", "策略执行"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_account), _translate("MainWindow", "交易账号"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_plus), _translate("MainWindow", "增值服务"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_algorithmtrading),
                                    _translate("MainWindow", "算法交易"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_instrument), _translate("MainWindow", "策略执行"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_marketdata), _translate("MainWindow", "Tick数据"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_listtdlog), _translate("MainWindow", "今日交易日志"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_listmdlog), _translate("MainWindow", "今日行情日志"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_historytd), _translate("MainWindow", "历史交易日志"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_historymd), _translate("MainWindow", "历史行情日志"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_data), _translate("MainWindow", "数据"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_report), _translate("MainWindow", "回测报告"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_result), _translate("MainWindow", "参数优化"))
        self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_faq), _translate("MainWindow", "常见问题"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "交易主界面"))
        self.groupBox_2.setTitle(_translate("MainWindow", "GroupBox"))
        self.label.setText(_translate("MainWindow", "TextLabel"))
        self.radioButton.setText(_translate("MainWindow", "RadioB&utton"))
        self.checkBox.setText(_translate("MainWindow", "CheckBox"))
        self.checkBox_2.setText(_translate("MainWindow", "CheckBox Tristate"))
        self.treeWidget.headerItem().setText(8, _translate("MainWindow", "qdz"))
        __sortingEnabled = self.treeWidget.isSortingEnabled()
        self.treeWidget.setSortingEnabled(False)
        self.treeWidget.topLevelItem(0).setText(0, _translate("MainWindow", "qzd"))
        self.treeWidget.topLevelItem(1).setText(0, _translate("MainWindow", "effefe"))
        self.treeWidget.setSortingEnabled(__sortingEnabled)
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "选项设置"))
        self.Button_Start.setText(_translate("MainWindow", "启动策略自动交易（已停止）"))
        self.Button_Stop.setText(_translate("MainWindow", "停止策略自动交易（运行中）"))
        # self.menu_a_popup.setText(_translate("MainWindow", "menu_a_popup"))
        self.menu_b_popup.setText(_translate("MainWindow", "交易功能项"))
        # self.menu_c_popup.setText(_translate("MainWindow", "menu_c_popup"))
        self.toolButton.setText(_translate("MainWindow", "..."))
        self.menuMenu_nav1.setTitle(_translate("MainWindow", "&底层Dll日志"))
        self.menuMenu_nav2.setTitle(_translate("MainWindow", "&策略管理器"))
        self.menuMenu_nav3.setTitle(_translate("MainWindow", "&K线数据来源"))
        self.menuSubmenu_2.setTitle(_translate("MainWindow", "&Submenu 2"))
        # self.dockWidget1.setWindowTitle(_translate("MainWindow", "&Dock widget 1"))
        self.dockWidget1.setWindowTitle(_translate("MainWindow", "实时行情和资金曲线(根据Tick实时生成K线)"))
        self.dockWidget1.setFeatures(QDockWidget.NoDockWidgetFeatures)
        self.comboBox_kline.setItemText(0, _translate("MainWindow", "K线周期: M1"))
        self.comboBox_kline.setItemText(1, _translate("MainWindow", "K线周期: M3"))
        self.comboBox_kline.setItemText(2, _translate("MainWindow", "K线周期: M5"))
        self.comboBox_kline.setItemText(3, _translate("MainWindow", "K线周期: M10"))
        self.comboBox_kline.setItemText(4, _translate("MainWindow", "K线周期: M15"))
        self.comboBox_kline.setItemText(5, _translate("MainWindow", "K线周期: M30"))
        self.comboBox_kline.setItemText(6, _translate("MainWindow", "K线周期: M60"))
        self.comboBox_kline.setItemText(7, _translate("MainWindow", "K线周期: D1"))
        self.comboBox_exchange.setItemText(0, _translate("MainWindow", "ALL,全部交易所"))
        self.comboBox_exchange.setItemText(1, _translate("MainWindow", "SHFE,上期所"))
        self.comboBox_exchange.setItemText(2, _translate("MainWindow", "DCE,大商所"))
        self.comboBox_exchange.setItemText(3, _translate("MainWindow", "CZCE,郑商所"))
        self.comboBox_exchange.setItemText(4, _translate("MainWindow", "CFFEX,中金所"))
        self.comboBox_exchange.setItemText(5, _translate("MainWindow", "INE,能源所"))
        self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar"))
        self.dockWidget2.setWindowTitle(_translate("MainWindow", "量化回测参数优化"))
        self.dockWidget2.setFeatures(QDockWidget.NoDockWidgetFeatures)
        self.Navgiate1.setText(_translate("MainWindow", "&VNPY官网"))
        self.Navgiate2.setText(_translate("MainWindow", "&VNTrader官网"))
        self.Navgiate3.setText(_translate("MainWindow", "&VNPY知乎"))
        self.Navgiate4.setText(_translate("MainWindow", "&知乎视频"))
        self.Navgiate5.setText(_translate("MainWindow", "&期货低佣金开户"))
        self.Navgiate6.setText(_translate("MainWindow", "&量化资源列表"))
        self.Navgiate2.setToolTip(_translate("MainWindow", "submenu"))
        self.Navgiate1_C.setText(_translate("MainWindow", "一键平仓"))
        self.Button_OpenDll.setText(_translate("MainWindow", "&开启DLL数据显示"))
        self.Button_CloseDll.setText(_translate("MainWindow", "&关闭DLL数据显示"))
        self.Button_StrategyManage_SingleThread.setText(_translate("MainWindow", "&Python单线程管理(仅支持.py策略文件类型)"))
        self.Button_StrategyManage_MulitProcess.setText(
            _translate("MainWindow", "&C++多进程管理（支持.py和.dll策略文件类型）（暂不支持，等待更新）"))
        self.Button_KlineSource_RealTimeTick.setText(_translate("MainWindow", "&实时TICK生成K线"))
        self.Button_KlineSource_ServerToday.setText(_translate("MainWindow", "&实时TICK生成K线 + 从服务器补齐1日K线"))
        self.Button_KlineSource_ServerMultiday.setText(
            _translate("MainWindow", "&实时TICK生成K线 + 从服务器补齐多日K线（增值服务Plus会员激活）"))
        self.Navgiate1.triggered.connect(self.Function_OpenUrl_VNPY)
        self.Navgiate2.triggered.connect(self.Function_OpenUrl_VNTRADER)
        self.Navgiate3.triggered.connect(self.Function_OpenUrl_ZHIHU)
        self.Navgiate4.triggered.connect(self.Function_OpenUrl_ZHIHUVIDEO)
        self.Navgiate5.triggered.connect(self.Function_OpenUrl_KAIHU)
        self.Navgiate6.triggered.connect(self.Function_OpenUrl_COOLQUANT)
        self.Button_OpenDll.triggered.connect(self.Function_OpenDllLog)
        self.Button_CloseDll.triggered.connect(self.Function_CloseDllLog)
        self.Button_StrategyManage_SingleThread.triggered.connect(self.Function_EnableStrategyManage_SingleThread)
        self.Button_StrategyManage_MulitProcess.triggered.connect(self.Function_EnableStrategyManage_MulitProcess)
        self.Button_KlineSource_RealTimeTick.triggered.connect(self.Function_KlineSource_RealTimeTick)
        self.Button_KlineSource_ServerToday.triggered.connect(self.Function_KlineSource_ServerToday)
        self.Button_KlineSource_ServerMultiday.triggered.connect(self.Function_KlineSource_ServerMultiday)
        self.Button_Start.clicked.connect(self.OnStart)
        self.Button_Stop.clicked.connect(self.OnStop)
        # 策略说明按钮
        self.Button_StrategyInstructions.clicked.connect(self.Function_StrategyInstructions)
        self.Button_StrategyFunction.clicked.connect(self.Function_StrategyInstructions)
        # 添加投资者账户按钮
        self.Button_AddInvestor.clicked.connect(self.Function_AddInvestor)
        # 修改投资者账户按钮
        self.Button_ModifyInvestor.clicked.connect(self.Function_ModifyInvestor)
        # 注册SIMNOW账户
        self.Button_Simnow.clicked.connect(self.Function_OpenUrl_SIMNOW)
        # 开立实盘账户（低佣金开户，A级期货公司）
        self.Button_Kaihu.clicked.connect(self.Function_OpenUrl_KAIHU)
        # Plus会员说明
        self.Button_Plus.clicked.connect(self.Function_OpenUrl_Plus)
        # VNPY社区
        self.Button_Community.clicked.connect(self.Function_OpenUrl_Community)
        # 绑定期货账号
        self.Button_BandPlus.clicked.connect(self.Function_OpenUrl_BandPlus)
        # 购买Plus
        self.Button_Buyplus.clicked.connect(self.Function_OpenUrl_Buyplus)
        self.Button_SetServiceUser.clicked.connect(self.Function_OpenUrl_VNPY)
        self.Button_BuyService.clicked.connect(self.Function_OpenUrl_VNPY)
        self.Button_AddStrategy.clicked.connect(self.function_scanstrategy)
        self.Button_OpenStrategyPath.clicked.connect(self.Function_OpenStrategyPath)

        self.Button_ConditionCombination.clicked.connect(self.Function_Buttonclicke0)
        self.Button_TalibCondition.clicked.connect(self.Function_Buttonclicke0)



        self.Button_OpenAlgorithmicTradingPath.clicked.connect(self.Function_OpenAlgorithmicTradingPath)
        self.Button_OpenBackTestingPath.clicked.connect(self.Function_OpenBackTestingPath)
        self.Button_ClearTodayMdLog.clicked.connect(self.Function_ClearTodayMdLog)
        self.Button_ClearTodayTdLog.clicked.connect(self.Function_ClearTodayTdLog)
        self.Button_FaqDevelopmentEnvironment.clicked.connect(self.Function_FaqDevelopmentEnvironment)
        self.Button_FaqKaihu.clicked.connect(self.Function_FaqKAIHU)
        self.function_scanstrategy()
        self.function_scantdhistorylog()
        self.function_scanmdhistorylog()
